
Looping Through a List –
Sometimes you may want to loop through a list and do some kind of operation on them. For that you can use a For loop.
Let’s say you have a list of numbers in a list and you want to get every even numbers from this list.
In [13]: numbers
Out[13]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
In [14]: even_numbers = []
In [15]: for num in numbers:
...: if num % 2 == 0:
...: even_numbers.append(num)
...:
In [16]: even_numbers
Out[16]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Here we have a list with numbers from 0 to 20 and we want to get all the even numbers from this list. To do that first we created an empty list to store all those values. Then we run a for loop which tells python to give each items in the numbers list one by one each time we go through the loop and store it in the num variable. Then the next line checks whether the number is divisible by 2 or not, if it is then we store that number into the even numbers list otherwise we don’t do anything. The % is the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It’s used to get the remainder of a division problem.
Related Posts –
1 . Append in Python – Adding Elements to the End of a List