Use for item in list
syntax to iterate over a list in Python. By using this for loop syntax you can iterate any sequence objects (string
, list, tuple
, set, 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.
1. Quick Examples to Iterate Over a List using For Loop
If you are in a hurry, below are some quick examples of how to iterate over a list using for
loop and while loop.
# Quick examples to iterate over a list
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.
Using a for
loop to iterate over a Python list is a common and straightforward approach. For example, the for
loop iterates over each element in the courses
list, and the variable x
takes on the value of each element in turn. The print(x)
statement then prints each course name to the console.
# Iterate over the list using for loop
courses = ["java", "python", "pandas"]
for x in courses:
print(x)
Yields below output.
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).
Use 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
The enumerate()
method can be used for any iterable objects such as list, range, etc. 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(iterable_object,start=0)
- The
enumerate()
method can be used for any iterable objects such as list, and range. - Using
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). Usestart
parm 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))
# Output:
# <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))
# Output:
# [(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
You can use the enumerate()
function to iterate over a list and get both the index and the corresponding value. For example, enumerate(courses)
returns pairs of index and corresponding value during each iteration of the for
loop. The loop variable index
represents the index of the current element, and course
represents the value of the current element.
# Using enumerate() to iterate over a list
courses=['java','python','pandas','sparks']
for index , item in enumerate(courses):
print(index,item)
# Output:
# 0 java
# 1 python
# 2 pandas
# 3 sparks
3.4 Start Loop Indexing with Non-Zero Value
If you want to start the loop indexing with a non-zero value, you can use the enumerate()
function and specify the start
parameter.
In this example, enumerate(courses, start=1)
starts the index from 1 instead of the default 0. The loop then prints the index and the corresponding course for each element in the list.
# Start loop indexing with non zero value
courses=['java','python','pandas','sparks']
for index , item in enumerate(courses,start=1):
print(index,item)
# Output:
# 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 for
loops.
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)
# Output:
# [40, 20, 80, 100]
According to the above example in the list comprehension, List
represents iterable object x
represents item
and x*2
represents expression.
4.2 Use A List Comprehension To Iterate Over List
Using a list comprehension to iterate over the courses
list and create a new list of tuples, where each tuple contains the index and the corresponding course from the original 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))])
# Output:
# [[0, 'java'], [1, 'python'], [2, 'pandas'], [3, 'sparks']]
We got 4 lists as an output, containing the index and its corresponding value in courses
.
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
In 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 False
.
Everything in 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 True
.
We can exit from the while loop using the break statement
.
Use 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
# Output:
# 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 False
.
# Using while loop iterate over a list
courses = ["java","python","pandas","sparks"]
i = 0
while i < len(courses):
print(courses[i])
i += 1
# Output:
# 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 lists
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)
# Output:
# 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.
Syntax
lambda arguments: expression
The lambda function along with a Python map() function can be used to iterate a list easily.
Python 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)
# Output:
# [6, 8, 10, 12, 14]
Frequently Asked Questions On Python Iterate Over List
You can iterate over a list in Python using a for
loop. For example, the for
loop iterates over each element (item
) in the list (my_list
).
You can use a while
loop to iterate over a list in Python by manually managing an index.
You can use the enumerate
function in Python to iterate over a list with both index and value. For example, the enumerate
function returns pairs of index and corresponding values from the list during each iteration of the for
loop. The loop variable index
represents the index of the current element, and item
represents the value of the current element. You can then use these values as needed within the loop.
List comprehension is a concise and readable way to create lists in Python. It provides a more compact syntax for generating lists by applying an expression to each item in an existing iterable (such as a list) and optionally applying a condition to filter the items.
You can use the range
and len
functions to iterate over a list. In addition to the for
loop and list comprehension, there are a couple of other ways to iterate over a list in Python.
Conclusion
In this article, you have learned multiple ways to iterate over a Python list by using for
loop, range()
, enumerate()
, list comprehension
, and whil
e loop. You have also learned the basic idea of NumPy
and lambda
function while iterating items in the list.
Happy learning !!
Related Articles
- 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