DEV Community

Cover image for Creating Lists in Python: List Comprehension vs. For Loop
Sarah Jones
Sarah Jones

Posted on

Creating Lists in Python: List Comprehension vs. For Loop

Considered to be the most common data structure in Python, lists are used to store multiple items within a single variable.

color_list = ["yellow", "green", "red"]

Because there are other ways to store data in Python, it’s important to understand what makes a list a list:

A list…

  • Can store all types of data
  • Is indexed: Each item in a list has a set location. The first item has index [0], the second item has index [1], etc.
  • Is mutable: Elements within a list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created
  • Contains items that can be repeated: Because lists are indexed, they can have items with the same value.

One way to create a list in Python, is by using a for loop.

Create A List Using A For Loop:

  1. Create an empty list: name_tag_list = []
  2. Loop over the parameters: for name in names:
  3. Append each element to the end of the list: name_tag_list.append(f"Hello, my name is {name}.")
  4. Return the list, which is no longer empty: return name_tag_list
def nametag_creator(names):
   name_tag_list = []
   for name in names:
       name_tag_list.append(f"Hello, my name is {name}.")
   return name_tag_list
Enter fullscreen mode Exit fullscreen mode

While using a for loop to create a list works (and is usually the first list creation method you will learn), Python allows us to instantiate a list object and perform a for loop to populate its values in a single line. This can be done using list comprehension.

Create A List Using List Comprehension:

  1. Create new list and assign its values in one line

List Comprehension Syntax:
new_list = [optional_operation(item) for item in old_list if optional_condition == True]

  • optional_operation(item): f"Hello, my name is {name}."
  • item: name
  • old_list: names
def name_tag_creator(names):
   return [f"Hello, my name is {name}." for name in names]
Enter fullscreen mode Exit fullscreen mode

When comparing the two name_tag_creator functions side by side, you will see that there are a lot of similarities. In this example, utilizing list comprehension (rather than a for loop) allowed us to create a new list, iterate, and fill the new list, all at once.

At this point you might be thinking, “Wow, using list comprehension allowed us to really cut down on the number of code lines written. Why would we ever not want to use list comprehension?

Well, it’s always essential that we consider readability. James Timmins says it best in his article “When to Use a List Comprehension in Python”:

“While the single-line nested list comprehension might seem more Pythonic, what’s most important is to write code that your team can easily understand and modify. When you choose your approach, you’ll have to make a judgment call based on whether you think the comprehension helps or hurts readability.”

Another instance where it makes sense to not utilize list comprehension, is when working with big datasets. List comprehension loads the entire output list into memory, meaning big datasets have the potential to use a lot of memory. To ensure that we don’t bog down servers, we could utilize generator expressions rather than list comprehensions.

Conclusion: In Python, for loops and list comprehensions are both great ways to create a list. When you first start working in Python, I recommend you begin with a for loop. Once you have mastered how a for loop can be used to create a list, you can then transpose that into a list comprehension. Happy coding!

Resources:
"Intro to Data Structures." Canvas - Flatiron School, Accessed 10 May 2023.
"List Comprehensions and Generator Expressions." Canvas - Flatiron School, Accessed 10 May 2023.
"Python Lists." W3Schools, www.w3schools.com/python/python_lists.asp. Accessed 11 May 2023.
Great Learning Team, and Karuna Kumari. "Understanding Mutable and Immutable in Python." Great Learning, www.mygreatlearning.com/blog/understanding-mutable-and-immutable-in-python/#:~:text=3.,the%20list%20has%20been%20created. Accessed 10 May 2023.
Timmins, James. "When to Use a List Comprehension in Python." Real Python, 6 Nov. 2019, realpython.com/list-comprehension-python/. Accessed 11 May 2023.

Top comments (0)