for loop in Python
List is a collection of objects, so we can loop through the list and extract the objects each at a time. consider the following to know more.
Iterate over a list using 'for' loop in Python
The 'for' loop in Python is different form the 'for' loop in the other programming languages.
In Python, the 'for' loop does not require any update to be done. It automatically update after each iteration.
Python 'for' loop syntax
Example
Input
2
3
4
5
'for' loop over list with range() method
Loop over a list, like above can be done with the range() method.
Program
Input
Output
2
3
4
5
Program
Input
Output
3
4
5
Program
Input
b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output
'for' loop over list with enumerate() method
The enumerate() method enumerates the list, with numbers.
Following is an example to enumerate the list.
Program
>>> b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Here is an example, how you can fetch the content, got after enumerating the list. Both, list value and the enumerated value.
Program
Input
for i, j in list(enumerate(b)):
print("Index: ", i, " Value: ", j)
Output
Index: 1 Value: 2
Index: 2 Value: 3
Index: 3 Value: 4
Index: 4 Value: 5
List comprehension
List comprehension with 'for' loop gives a lot of information with 1 line of sentence and is more easy and readable.
Creating a list using list comprehension with 'for' loop
Following is the program which will create a list without using list comprehension mechanism.
Program
Now this is how you can create a list using list comprehension with just one line of code. Which is so easy.
Program
>>> compre = [value for value in range(0, 10)]
List comprehension with an expression
Let's put an expression at the beginning, for some computation for the list comprehension.
Here is an example, which will raise each value with the power of 2.
Program
List / tuple collection with list comprehension
Creation of list which will be the collection of list / tuple, using list comprehension.
The following code will have the collection of tuples, in which the two elements of each tuple will not be equal to each other.
Program
List comprehension with a function
Introducing a function at the beginning of the for loop in list comprehension, is also possible.
List comprehension with built-in function
Program
>>> a = [1, 2, 3]
List comprehension using the user defined function
First of all we define a function, and then introduce it into the list comprehension.
Program
Input
Output
[3, 4, 5, 6, 7]
Post a Comment
If you have any query, feel free to ask.