In this tutorial, you’ll learn how to iterate (or loop) over a list in Python. You’ll learn how to iterate with for loops, while loops, comprehensions, and more. What’s more, is that you’ll learn when each of these methods is the best method to use. Given that there are many different ways of accomplishing this, it can be helpful to understand which method to use. Show
Python lists are one of the cornerstone data structures in the language. They are ordered and indexable, meaning that their order matters and that you can access items based on their order. They’re also heterogeneous, meaning that they can hold many different data types. Because of their versatility, knowing how to work with them is an important skill for a Pythonista of any level. By the end of this tutorial, you’ll have learned:
A Guide to Iterating Over a List in PythonThe table below breaks down the different methods in which you can loop over a list in Python. To learn more about each of these methods, keep reading for a deeper dive.
How to Loop Over a List in Python with a For LoopOne of the simplest ways to loop over a list in Python is by using a for loop. A for loop allows you to iterate over an interable object (like a list) and perform a given action. This approach is intuitive because it loops over each item in the list (unless explicitly stopped). Let’s take a look at an example of how we can loop over a list of numbers in Python using a for loop: # Looping Over a List in Python with a For Loop numbers = [1, 2, 3, 4, 5] for number in numbers: print(number) # Returns: # 1 # 2 # 3 # 4 # 5We’re able to loop over each item in the list by using any iterator name that we want to use. In this case, we used the word number in order to make our code cleaner to write and to read. How to Loop Over a List in Python with a While LoopIn this section, you’ll learn how to loop over a list in Python using a while loop. While a for loop is an example of definite iteration, a while loop is an example of indefinite iteration. This means that the loop will continue to iterate until it is stopped. Let’s see how we can use a Python while loop to iterate over each item in a list by taking a look at an example: # Using a Python While Loop to Iterate Over a List numbers = [1, 2, 3, 4, 5] i = 0 while i < len(numbers): print(numbers[i]) i += 1 # Returns: # 1 # 2 # 3 # 4 # 5Let’s break down what we did here:
How to Loop Over a List in Python with a List ComprehensionIn this section, you’ll learn a unique way of looping over each item in a list. Python comprehensions are a compact way of iterating over a list. Generally, they are used to create lists, either from scratch or by modifying items within the list. Let’s see how we can use a Python list comprehension to loop over a list. In this example, we’ll use a comprehension to print out each item in a list. For more examples of how to use these powerful structures, check out my complete tutorial on list comprehensions. # Using List Comprehensions to Iterate Over a List numbers = [1, 2, 3, 4, 5] [print(number) for number in numbers] # Returns: # 1 # 2 # 3 # 4 # 5How to Iterate Over a List with Index Items Using RangeThere may be times that you want to iterate over a list by accessing both the item and the index of the item. We can do this by making use of the range() function. I’m including this method mostly for completeness, because in the following section you’ll learn a better way of handling this using the enumerate() function. That said, it’s a commonly used method to iterate over a Python list while accessing both the index and the item. Let’s see what this looks like: How to Iterate Over a List with enumerateSimilar to the example shown above, we can easily loop over each item in a list and access its index using the Python enumerate() function. The enumerate() function returns both the index and the item, meaning you can easily unpack them in your loop. For more details on the enumerate() function, check out my in-depth guide. Let’s see what this looks like: # Iterating Over a List with Python's enumerate() numbers = [1, 2, 3, 4, 5] for idx, number in enumerate(numbers): print(idx, number) # Returns: # 0 1 # 1 2 # 2 3 # 3 4 # 4 5How to Iterate Over Multiple Python Lists Element-WiseIn this section, you’ll learn how to iterate over multiple Python lists at the same time using the Python zip() function. The function lets you iterate over multiple lists at the same time, meaning that the first item of each list is accessed, then the second, and so on. To learn more about how this function works, check out my in-depth tutorial. Let’s take a look at an example of how we can loop over two lists at once: # Looping Over Multiple Lists Element-wise in Python numbers = [1, 2, 3, 4, 5] numbers2 = [6, 7, 8, 9, 10] for num1, num2 in zip(numbers, numbers2): print(num1, num2) # Returns: # 1 6 # 2 7 # 3 8 # 4 9 # 5 10Let’s break down what we did here:
In the next section, you’ll learn how to iterate over list items and manipulate them. How to Iterate Over and Manipulate Python ListsIn this final section, you’ll learn how to use the Python map() function to iterate over list items and manipulate them by applying a transformation function. The function takes a transformation function object and a list as its input and returns the manipulated list. To learn more about the Python map() function, take a look at my in-depth guide here. Let’s take a look at an example: # Using map() to Iterate Over a List and Manipulate its Items numbers = [1, 2, 3, 4, 5] transformed = list(map(lambda x: x * 2, numbers)) print(transformed) # Returns: # [2, 4, 6, 8, 10]Let’s break down what we did here:
ConclusionIn this tutorial, you learned how to iterate (or loop) over a list in Python in many different ways. You learned what method is the best for which situation. You learned how to use a for loop, a while loop, and a list comprehension. Then, you learned how to use the range() function and the enumerate() function to iterate over lists and indices. Finally, you learned how to iterate over two lists element-wise as well as how to iterate and transform list items. Additional ResourcesTo learn more about related topics, check out the tutorials below:
How to iterate through Java List? This tutorial demonstrates the use of ArrayList, Iterator and a List. There are 7 ways you can iterate through List.
Java Example:You need JDK 13 to run below program as point-5 above uses stream() util. void java.util.stream.Stream.forEach(Consumer<? super String> action) performs an action for each element of this stream. Output:==============> 1. Simple For loop Example. Facebook Paypal Google Yahoo ==============> 2. New Enhanced For loop Example.. Facebook Paypal Google Yahoo ==============> 3. Iterator Example... Facebook Paypal Google Yahoo ==============> 4. ListIterator Example... Facebook Paypal Google Yahoo ==============> 5. While Loop Example.... Facebook Paypal Google Yahoo ==============> 6. Iterable.forEach() Example.... Facebook Paypal Google Yahoo ==============> 7. Stream.forEach() Example.... Facebook Paypal Google Yahoo Process finished with exit code 0If you liked this article, then please share it on social media. Still have any questions about an article, leave us a comment. |