avatarArtturi Jalli

Summary

The website content provides an in-depth guide on six different methods to iterate over a list in Python, including for loops, range() method, while loops, list comprehensions, enumerate() function, and using lambda expressions with the map() method.

Abstract

The article titled "Python Loop Through Lists in 6 Ways" is a comprehensive tutorial aimed at Python programmers who want to learn various techniques for iterating over lists. It begins by explaining the fundamental for loop and its syntax, then moves on to demonstrate how to use the range() method to iterate with index awareness. The article also covers while loops as an alternative to for loops, emphasizing the need for index tracking. List comprehensions are introduced as a concise and efficient way to create new lists from existing ones, with examples showing both basic usage and filtering capabilities. The enumerate() function is presented as a cleaner approach to accessing both elements and their indices in a list. Lastly, the article explores the use of lambda functions in conjunction with the map() method to apply a function to each item in a list. The author concludes by encouraging readers to apply these methods to improve their coding efficiency and readability.

Opinions

  • The author suggests that list comprehensions can improve code readability and are more efficient than regular functions and loops for list creation, but cautions against overly complex one-liners.
  • The enumerate() function is recommended for simplifying code when both the value and index of list elements are needed during iteration.
  • Lambda functions are touted as useful for short-term functionality without the need for separate method definitions, particularly when used with the map() function to apply operations across list elements.
  • The article includes a disclaimer about affiliate links, indicating that the author may receive compensation if readers follow provided links to become Medium members.
  • The author expresses a personal opinion by recommending an AI service, ZAI.chat, as a cost-effective alternative to ChatGPT Plus (GPT-4), suggesting its value for readers interested in AI services.

Python Loop Through Lists in 6 Ways

Learn 6 ways to iterate a list in Python

Learn Python—Loop Through Lists

In Python, a list is a commonly used collection where you can store multiple values, such as integers or strings. As the lists tend to get big, it is useful to have a tool to iterate over them without having to do it manually. Today you are going to learn some basics of Python: Loop through lists in 6 useful ways.

Disclaimer: This post contains affiliate links.

1. For Loops

In Python, a for loop is a commonly used construct to iterate over a sequence (such as a list, tuple, or dictionary). Here is the basic syntax of a for loop:

for val in sequence:
    # some action here

The val is the variable to which the element inside the sequence is assigned on each iteration.

As an example, let’s use the for loop to iterate over a list of numbers and print each number to the console:

Output:

1
2
3
4
5

2. Loop Through a List Using Range() Method

Sometimes you may want to use the traditional approach to looping: iterate from number x to number y. This can be useful when you do not only need the value but also the index of that value.

To do this, you can use the built-in range() method. The range() method works such that it returns a sequence of integers from a starting point to one before the endpoint. For instance, create a list of numbers 0...4:

print(list(range(0,5)))

Output:

[0, 1, 2, 3, 4]

As an example, let’s print the names of the people in line and their relative position in the line. This can be done by iterating numbers from 0 until the length of the queue with the help of range() method:

Output:

Jack is at 1. position
Ann is at 2. position
Sofie is at 3. position

3. While Loops

With a while loop, you can execute statements as long as a condition is true. Similar to for loops you can use while loops to iterate over lists and other iterables.

For instance, let’s iterate over a list of numbers. To do this with a while loop, you need to know the length of the list and keep track of an index. This is because you want to end the loop when you reach the end of the list (i.e. when the condition index < list_length doesn’t hold any more):

Output:

1
2
3

4. One-Liner Loops with List Comprehension

List comprehension is a really useful built-in feature in Python. It makes it possible to replace a for loop with a one-liner expression. This can be a really nice readability improvement if used properly.

This is the general syntax for using a list comprehension:

[expression for element in input_list]

For example, let’s print out the numbers from a list of numbers using list comprehension:

Output:

1
2
3

List comprehensions are mostly used to construct a new list from an existing one. To demonstrate this, let’s square a list of numbers into a new list:

Output:

[1, 4, 9, 16]

Also, it is possible to add a condition to the end of a list comprehension expression.

For instance, let’s create a list of even numbers by filtering a list of numbers to a new list:

Output:

[2, 4, 6, 8, 10]

To take home:

  • List comprehension is a neat way to create new lists based on existing ones.
  • List comprehension is actually a bit more efficient than regular functions and loops for creating lists.
  • Keep in mind you should avoid writing lengthy one-liner list comprehensions if it compromises code readability.
  • It is also good to know that every list comprehension can be written as a for loop, but not the other way around.

5. Enumerate() Function

Python’s built-in enumerate() function assigns a counter to an iterable (e.g. a list). This means you can use it to iterate over a list and always know the index of the current iteration. This nicely simplifies the code and you don’t need to worry about handling the index.

Let’s repeat one of the earlier examples by printing the names and the positions of a group of people in a queue using enumerate().

Output:

Jack is at 1. position
Ann is at 2. position
Sofie is at 3. position

Comparing this code to the approach in the 2. section you can see how the code became a bit more concise and shorter without sacrificing the code readability.

6. Use a Lambda Expression with Map() Method

Lambda Functions

In Python, a lambda function is a function without a name. It takes any number of arguments and only has one expression. To demonstrate, here is a lambda function that squares a number:

lambda x : x ** 2

You could use this e.g. as follows (although this is not the purpose):

squared_num = (lambda x : x ** 2)(4.0)
print(squared_num)

Output:

16.0

Lambda functions are useful when the functionality is needed only for a short period of time. In other words, when you don’t want to waste resources by creating a separate method.

Map() Function

The map() function may sometimes replace a regular for or while loop. The map() applies a function for each element in a list and returns another list as a map object. This map object can be converted to a list with the list() function.

Use Map() and Lambda to Loop Through a List

Let’s square a list of numbers by passing a lambda function that squares numbers into the map() function:

Output:

[1, 4, 9, 16, 25]

All this code does is takes the numbers and squares each using the lambda x: x ** 2 function + adds the result to the new list called squares.

Conclusion

Thanks for reading. I hope you learned something new today.

Become a Top Coder

Did you like this article?

Become a member at Medium.com to read top stories by experts in the field.

Disclaimer: By joining via the provided link, I earn a small commission at no extra cost for you :)

You May Find Insightful

Python
Data Science
Programming
Software Development
Education
Recommended from ReadMedium