In this Python tutorial, we will walk through how to use the range() function to iterate through a list in Python using illustrative examples.
Python provides a variety of methods for interacting with lists. One of the most common tasks that a programmer may need to accomplish is iterating through a Python list. In Python, this can be done using the range() function, which generates a sequence of numbers that we can use to access list items.
What is the range() function in Python
The range() function in Python generates a sequence of numbers starting from 0 by default, and increments by 1 (also by default), and stops before a specified number.
The syntax for the range() function in Python is as follows:
range(start, stop, step)
Where:
- Start:– (Upper limit/Optional) An integer number specifying at which position to start. The default is 0.
- Stop:– (Lower limit)An integer number specifying at which position to end.
- Step:– (Optional) An integer number specifying the incrementation. The default is 1.
The range() function in Python only works with integer values(positive or negative). If we use a float or a non-integer type of value, we will get a TypeError.
Using the range() function to iterate through a list in Python
Now, let’s dive into how we can use the range() function to iterate through a list in Python. Let’s take a list of some USA states as an example.
usa_states = ["Alaska", "California", "Hawaii", "New Jersey", "New York", "Ohio", "Texas", "Washington"]
To iterate through this Python list using the range() function, we would do something like the following:
usa_states = ["Alaska", "California", "Hawaii", "New Jersey", "New York", "Ohio", "Texas", "Washington"]
for i in range(0, 8, 1):
print(usa_states[i])
Note: We can use the negative index also, to do so.
In the code above, the range() function in Python is used to generate a sequence of numbers from 0 to 8 without any interval as the value of the step is the same as the default. The for loop then iterates through these numbers, and each number is used as an index to access and print the corresponding item in the usa_states list.
Or we can use, the len() function as a stop parameter for the range() function
usa_states = ["Alaska", "California", "Hawaii", "New Jersey", "New York", "Ohio", "Texas", "Washington"]
for i in range(len(usa_states)):
print(usa_states[i])
In this code of Python, the range() function is used to generate a sequence of numbers from 0 to the length of the usa_states list.
Output: for both cases, the result will be the same as len(usa_states) is 8, which is the stop value in the first one.
Alaska
California
Hawaii
New Jersey
New York
Ohio
Texas
Washington
Use Cases of Python range() to iterate through a list
One might wonder, why the range() method is when we can simply iterate over the Python list directly like this:
for state in usa_states:
print(state)
While it’s true that we can iterate through a list directly in Python, there are certain situations where using range() can be beneficial:
- Modifying List Elements
- Accessing Elements in Multiple Lists Simultaneously
- Iterating Over Part of a List
Let’s see them one by one with suitable examples:
Case-1: Modifying Python list elements using the range() function
If we need to modify the elements of the Python list while iterating over it, we would need their indices. In that case, the range() function comes in handy.
In this example, we will multiply each element in a list by a factor of 2. This is an instance where we need to modify the elements of a Python list while iterating, and thus need to use the range() function:
numbers = [1, 2, 3, 4, 5]
factor = 2
for i in range(len(numbers)):
numbers[i] *= factor
print(numbers) # Outputs: [2, 4, 6, 8, 10]
The output is:
The Python list has been modified using the range() function.
Case-2: Accessing Elements in Multiple Lists Simultaneously using range() function in Python
If we have multiple Python lists of the same length and need to process elements at the same indices from these lists, we can use the range() function.
In this example, we will iterate through two Python lists simultaneously, using the index provided by the range() function to access corresponding elements from each list:
usa_states = ["California", "New York", "Texas"]
state_capitals = ["Sacramento", "Albany", "Austin"]
for i in range(len(usa_states)):
print(f"The capital of {usa_states[i]} is {state_capitals[i]}.")
The output is:
usa_states = ["California", "New York", "Texas"]
state_capitals = ["Sacramento", "Albany", "Austin"]
for i in range(len(usa_states)):
print(f"The capital of {usa_states[i]} is {state_capitals[i]}.")
This way we can use the range() function to access elements simultaneously of two Python lists.
Case-3: Iterating Over Part of a Python List using the range() function
With the range() function in Python, we can iterate over a slice of the Python list by defining the start and stop parameters of the range.
The range() function can be used with a step parameter to select every n-th element from a Python list. Let’s say we want to print every third element from a Python list of companies:
companies = ["Apple", "Microsoft", "Amazon", "Google", "Facebook", "Tesla", "Berkshire Hathaway", "Visa", "J&J", "Walmart"]
for i in range(0, len(companies), 3):
print(companies[i])
The output is: Here, the function will take 1st element and will skip 2, and then print the 3rd element. and will iterate until it will reach the stop value.
Apple
Google
Berkshire Hathaway
Walmart
This way we can use the range() function in Python to iterate over part of a list.
Conclusion:
In conclusion, while Python provides simpler ways to iterate through lists, the range() function provides greater flexibility, especially when it comes to tasks that require index-based operations in a Python list.
You may also want to read:
- Palindrome Program using function in Python
- Understanding Lambda Functions in Python | The Beauty of Anonymous Functions
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.