One of the main benefits of coding and programming is that tasks can easily be automated and replicated. This practice is evident in the very structure of programming languages and data structures. Often the center of a program revolves around iterating through values or objects.
With Python, there is a multitude of methods to iterate through lists and tuples. Some of these methods can be complicated. If you’re just learning about iteration in Python, you’ll be best served by learning the easier, more common interaction methods that can be applied to almost any situation. Here, I present 5 easy methods to iterate through Python lists and tuples.
The 5 easiest methods to iterate through a Python list or tuple are:
- List comprehension
I’ll demonstrate how to implement each of these methods and the situations each method is best suited for.
1. Iterate Through a Python List with a
for loop is the most common way to iterate through a Python list.
for loop implementation in Python is very simple, especially with a list a tuple.
The basic syntax is as follows.
for item in object: print(item)
In the case of a Python list,
object is the list and
item refers to an element in the list.
Let’s try this with the simple list defined below. The defined list consists of several numbers. We’ll write code to multiply each number by 2, then print it out.
First, we’ll define a list and a tuple that we’ll use throughout these examples.
my_list = [5, 3, 90, 23, 12] my_tuple = (8, 20, 4, 34, 98)
Now let’s loop through the list, multiply it by two, and print the result.
for x in my_list: print(x * 2)
Here’s what the result looks like.
10 6 180 46 24
for loop example works the same with a Python tuple as it does with a Python list. It is a flexible method that can be applied to a wide variety of situations. A
for loop is the most general way to iterate through an iterable in Python.
range() to Iterate Through a Python List
Instead of iterating through list or tuple items directly, the item index can be used to reference elements. As implied, the index specifies the location of each item in a list or tuple object. In Python, index values start at 0, so the first element in a list will have an index value of 0 and the last item will have an index of the list length minus 1.
A list element is retrieved using its index value as follows. The two examples show how to access the first and second elements of
my_list, which we created above.
my_list # first element my_list # second element
range() function generates a sequential list of numbers following a specific pattern. In the first example, we used a
for loop to iterate through the individual elements of a list. Here we’ll use a
for loop to iterate through the numbers generated by the
range() function and use those values to iterate through a list.
This may sound a little complicated but it’s an easy concept when you get the hang of it. It’s also very useful when you have multiple lists and you want to use corresponding elements for computations.
First, we’ll go through a simple example using the list we created above, then we’ll do an example with two lists.
Here, we use the
len() function to get the length of the list and generate the appropriate range for the indices.
for i in range(len(my_list)): print('index:', i, 'value:', my_list[i])
And here’s what the output looks like.
index: 0 value: 5 index: 1 value: 3 index: 2 value: 90 index: 3 value: 23 index: 4 value: 12
A benefit of using
range() is that the index value (
i in the above example) can be used to index multiple lists or tuples. Below, we’ll use the index,
i, to get values from both
my_tuple then multiply them.
for i in range(len(my_list)): print('list value:', my_list[i], 'tuple value:', my_tuple[i], 'multiplication', my_list[i] * my_tuple[i])
And the result.
list value: 5 tuple value: 8 multiplication 40 list value: 3 tuple value: 20 multiplication 60 list value: 90 tuple value: 4 multiplication 360 list value: 23 tuple value: 34 multiplication 782 list value: 12 tuple value: 98 multiplication 1176
3. Use List Comprehension to Iterate Through a Python List
Python list comprehension is a simple, concise way of iterating through lists (or tuples) to access or alter values. The result of list comprehension is another list (or other iterable, like a tuple) so you don’t need to write a full loop and append results to another iterable.
Let’s start out by accessing each item in
my_list. The following code creates a replicate of
[item for item in my_list]
[5, 3, 90, 23, 12]
Notice how the result of this operation is a list. This list is identical to the input,
Now let’s try a more realistic example. In this case, we’ll divide each element in the list by 2. Other functions and operations can be applied using the same method.
[item / 2.0 for item in my_list]
[2.5, 1.5, 45.0, 11.5, 6.0]
Notice how concise list comprehension is. You can write a single line of code that results in a list without needing to create or manage lists.
4. Iterate Through a Python List with a
while loop continues to execute a block of code while a condition is true. Python
while loops can be used to iterate through lists and tuples when the condition is tied to the index of the iterable.
The procedure for iterating through a Python list with a
while loop is this.
- Intialize a variable with a value of 0 to index the list, tuple, or other iterable (e.g.
i = 0)
- Start the
whileloop with the condition that the index must be less than the iterable’s length (e.g.
while i < len(my_list))
- Run code to be applied to each element of the iterable (e.g.
- Update the index variable (e.g.
i += 1)
Don’t forget Step 4! If you do it will result in an infinite loop. That means the condition for the while statement will always be true so the loop will keep executing the code for the same index and will never stop running. If this happens to you, and it will (it’s happened to me, and probably every other programmer), just close the program.
The below example uses a
while loop to print out the values for the list and tuple we defined at the beginning of this article.
i = 0 while i < len(my_list): print('index', i, 'value', my_list[i], 'tuple value', my_tuple[i]) i += 1
index 0 value 5 tuple value 8 index 1 value 3 tuple value 20 index 2 value 90 tuple value 4 index 3 value 23 tuple value 34 index 4 value 12 tuple value 98
while loops are a very flexible option for iteration in Python.
enumerate() to Iterate Through a Python List
enumerate() method you can iterate through a list or tuple while accessing both the index and value of the iterable (list or tuple) object. Using enumerate is similar to combining a basic
for loop and a
for loop that iterates by index.
A call to
enumerate() returns an enumerate object that is iterable and can be used in a loop. The enumerate object contains the index and value for each element in the iterable.
This should make more sense in the example below where we use
enumerate() to iterate through
for i, item in enumerate(my_list): print('index', i, 'item', item, 'tuple', my_tuple[i])
index 0 item 5 tuple 8 index 1 item 3 tuple 20 index 2 item 90 tuple 4 index 3 item 23 tuple 34 index 4 item 12 tuple 98
enumerate() method is very useful when you want to use both the index and value of an iterable object.
There are many, many ways to iterate through lists and tuples and with Python. However, many of those options are best reserved for specific situations. Here, I’ve presented five methods for iterating through Python lists and tuples that will work for most coding situations you will encounter.
for loops and
while loops will give you the most flexibility when iterating through lists and tuples. The tradeoff is that you will need to write a little more code to implement them. In Python, list comprehension is the most elegant and concise way to iterate through a list or tuple. While list comprehension works for many situations it is not as flexible as
Learn GIS From Industry Professionals
Whether you’re looking to take your GIS skills to the next level, or just getting started with GIS, we have a course for you! We’re constantly creating and curating more courses to help you improve your geospatial skills.
All of our courses are taught by industry professionals and include step-by-step video instruction so you don’t get lost in YouTube videos and blog posts, downloadable data so you can reproduce everything the instructor does, and code you can copy so you can avoid repetitive typing