for item in list syntax to iterate over a list in Python. By using this for loop syntax you can iterate any sequence objects (
range, or dictionary(dict)). A
list contains a collection of values so, we can iterate each value present in the list using Python for loop or while loop.
In this article, you will learn different ways to iterate through a python list.
Quick Examples to Iterate Over a List using For Loop
Following are some quick examples of how to iterate over a list using
for loop and while loop.
courses = ["java", "python", "pandas"] # Example 1: Iterate over the list using for loop for x in courses: print(x) # Example 2: Using range() to iterate over a list for x in range(len(courses)): print(courses[x]) # Example 3: Using enumerate() to iterate over a list for index , item in enumerate(courses): print(index, item) # Example 4: Use list comprehension to iterate over a list print([list((i, courses[i])) for i in range(len(courses))]) #Example 5: Using while loop iterate over a list i = 0 while i < len(courses): print(courses[i]) i += 1 # Example 6: Using Python NumPy module a = np.arange(4) for x in np.nditer(a): print(x) # Example 7: Using lambda function to iterate over a list list1 = [3,5,7,9,11] new_list= list(map(lambda x:x+3 , list1)) print(new_list)
Below I have explained these examples in detail by executing the code and sharing the output.
1. Use For Loop to Iterate Over a Python List
The easiest method to iterate the list in python programming is by using it with for loop. Below I have created a list called
courses and iterated over using for loop.
# Iterate over the list using for loop courses = ["java", "python", "pandas"] for x in courses: print(x)
Yields below output.
java python pandas
2. Use range() Function To Iterate Over A Python list
The range() method returns a sequence of integers. The
range() function starts from 0 and increments by 1(by default) and ends before an end number (n-1).
len(courses) to get the size of the list and use the size with
range() function to get the list of values starting from 0 by incrementing 1 until the size of the list. To retrieve the value from the list use
courses[x] within the body of for loop.
# Using range() to iterate over a list courses = ['java','python','pandas','sparks'] for x in range(len(courses)): print(courses[x])
Yields below output.
java python pandas sparks
3. Python For Loop With enumerate() To Iterate List
enumerate() method can be used for any iterable objects such as list, range e.tc. Using enumerate() method we can access an index of iterable objects and return enumerate objects.
3.1 Syntax of enumerate()
Following is the syntax of enumerate() function that I will be using rest of the article.
enumerate()method can be used for any iterable objects such as list, and range.
enumerate()method we can access an index of iterable objects.
- enumerate() method has two parameters: iterable objects( such as list, tuple) and start parameter.
enumerate()method starts with 0 (by default). Use
startparm to define the custom start position.
- It returns enumerate object.
The below example shows the type of the enumerate object.
# Using type() to get enumerate type courses = ["java","python","pandas"] courses_index = enumerate(courses) print(courses_index) print(type(courses_index)) # Outputs <enumerate object at 0x7fe3c12c83c0> <class 'enumerate'>
3.2 Convert enumerate to List
The enumerate() method combines indices to iterable objects and returns them as an enumerated object. This enumerated object can be easily converted to a list using a
list(). This is the easiest way of accessing both items and their indices at once. You need to understand this as it will give you insight into how enumerate provides you with an index.
# Convert enumerate object to list object courses = ["java","python","pandas"] courses_index = enumerate(courses) print(list(courses_index)) # Outputs [(0, 'java'), (1, 'python'), (2, 'pandas')]
As you see, the values in the list are now inside a tuple where the first value in the tuple is an index and the second is a value from a list.
3.3 Use enumerate() To Iterate Over a List
In Python when you use enumerate() to iterate the list, it returns an index and item for each element in a enumerate
# Using enumerate() to iterate over a list courses=['java','python','pandas','sparks'] for index , item in enumerate(courses): print(index,item) # Outputs 0 java 1 python 2 pandas 3 sparks
3.4 Start Loop Indexing with Non-Zero Value
You can change the start parameter to change the indexing. By default, it is 0. Now start loop indexing with a non-zero value(start=1).
# Start loop indexing with non zero value courses=['java','python','pandas','sparks'] for index , item in enumerate(courses,start=1): print(index,item) # Outputs 1 java 2 python 3 pandas 4 sparks
4. Using a List Comprehension to Iterate Over a List
List comprehension allows a lesser syntax if you want to create a new list based on an already existing list. Using list comprehension we can manipulate lists, more efficiently compared to functions and Python
4.1 Syntax of the List Comprehension
# Syntax of the list comprehension [expression for item in list]
list– Is a collection of elements.
item– Elements are present in the sequence which is iterable.
expression– Combination of operators and operands.
Let us take a simple example for a better understanding
# Using list comprehension manipulate list list = [20,10,40,50] products = [x*2 for x in list] print(products) # Outputs [40, 20, 80, 100]
According to the above example in the list comprehension,
List represents iterable object
x*2 represents expression.
4.2 Use A List Comprehension To Iterate Over List
# Use list comprehension to iterate over a list courses=['java','python','pandas','sparks'] print([list((i, courses[i])) for i in range(len(courses))]) # Outputs [[0, 'java'], [1, 'python'], [2, 'pandas'], [3, 'sparks']]
We got 4 lists as an output, containing the index and its corresponding value in
5. Use A While Loop To Iterate Over the List
The while loop in Python is used to iterate over a block of code as long as the test condition is true. It is used when we don’t know the number of times the code block will execute.
5.1 Syntax Of The While Loop
while(condition) : body of the loop
The process of the while loop, initially condition will be checked if only the
test condition is
True, the body of the code will execute. This process continues until the
test condition is
Python is an object, every object in Python has a boolean value. The boolean value of 0 or None is
False and the boolean value of non-zero value is
We can exit from the while loop using the
continue statement inside of the while loop to skip the current block of code.
Python supports nested while loops as-well.
Let’s take an example for better understanding,
# Using while loop print 'hello' i=1 while i <= 5: print("hello") i=i+1 #Outputs hello hello hello hello hello
5.2 Iterate Over A Python List Using While Loop
Using a while loop we can iterate over a Python list. In the following example, I have taken
courses as a list, it has been iterated with the help of
len(courses) using the while loop. Then it is processed based on the condition until the condition reach
# Using while loop iterate over a list courses = ["java","python","pandas","sparks"] i = 0 while i < len(courses): print(courses[i]) i += 1 #Outputs java python pandas sparks
6. Using Python NumPy Module With For Loop
Iterating means going through elements one by one. As we deal with multi-dimensional arrays in NumPy, we can do this using the basic
for loop of python. If we iterate on a 1-D array it will go through each element one by one.
Arrays support the iterator protocol and can be iterated over like Python
6.1 Single Array Iteration
The most basic task that can be done with the
nditer(iterator object) is to visit every element of an array. Each element is provided one by one using the standard Python iterator interface.
# Using Python NumPy module a = np.arange(7) for x in np.nditer(a): print(x) #outputs 0 1 2 3 4 5 6
From the above example
np.arange(7) creates a sequence of integers from 0 to 6.
7. Python For Loop Iterate a List Using Lambda Function
Python lambda function is an anonymous function.
lambda arguments: expression
The lambda function along with a Python map() function can be used to iterate a list easily.
map() method allows a lambda function as a parameter and returns a list. The function is called with all the items in the list and returned a new list, which contains all items respectively returned from that function.
# Using lambda function to iterate over a list list1 = [3,5,7,9,11] new_list= list(map(lambda x:x+3 , list1)) print(new_list) #Outputs [6, 8, 10, 12, 14]
In this article, you have learned multiple ways to iterate over a Python list by using
list comprehension, and
while loop. You have also learned the basic idea of
lambda function while iterating items in the list.
Happy learning !!
- For Loop with If Statement in Python
- For Loop Break Statement in Python
- For Loop Iterate Over an Array in Python
- For Loop Continue And Break in Python
- How to Perform Decrement for Loop in Python
- How to Increment for Loop in Python
- For Loop Enumerate in Python
- Get Counter Values in a for Loop in Python?
- Access Index in for Loop in Python
- Python Iterate Over a Dictionary