Python

How to Create a List in Python: Loops, Comprehensions, and More

If you’re working with Python for the first time, you might be interested in learning how to store data. For example, you might want to collect a list of exam scores, so you can average them. If so, the list data structure gets the job done. But, how do you create a list in Python? That’s the topic of today’s article.

As it turns out, there are a few different ways to create a list. First, we could create a list directly as follows: my_list = [0, 1, 2]. Alternatively, we could build that same list using a list comprehension: my_list = [i for in range(0, 3)]. Finally, if we need more control, we could build up our list using a loop and append(). In the remainder of this article, we’ll look at each solution in detail.

Problem Description

When it comes to working with different types of data in Python, it’s helpful to have some way to manage it. Luckily, Python supports and easy-to-use data structure for storing all kinds of data: the list.

In Python, the list is an array-like data structure which is dynamic in size. In other words, we don’t have to worry about knowing how many items we have before we create our list. For those of us who work in languages like Java or C, we’re used to being stuck with the following syntax:

int[] list = new int[10];

Luckily, Python has a much cleaner syntax. Specifically, we have two options:

  1. Create a list using the constructor: my_list = list()
  2. Or, create a list using an empty list: my_list = []

But, what if we want to populate that list? That’s the problem we’ll be tackling today. Fortunately, there are several solutions.

Solutions

At this point, we’ll take a look at a few ways to create a list in Python. As always, we’ll work our way from straightforward to more complex solutions. After that, we’ll compare each solution’s performance. At any rate, let’s dive in!

Create a List by Hand

One of the nice things about Python is that we can create a list by hand. In other words, if we know how we want to populate the list, we can write those contents out directly:

my_list = ["Crosby", "Malkin", "Letang", "Rust"]

In one line, we managed to create a variable called my_list. Then, we assigned it a literal list which contains a few Penguins players.

Now, if we want to interact with this list, we can. For instance, we could get any of the following information:

  • First player: my_list[0]
  • Last player: my_list[-1]
  • First two players: my_list[:2]
  • Every other player: my_list[::2]

If you’re interested in articles on list interaction, I’ve written a thing or two:

Otherwise, let’s look at a few other solutions.

Create a List with a Loop

Since lists in Python are dynamic, we don’t actually have to define them by hand. In other words, we can create an empty list and add items to it with a loop:

my_list = []
for i in range(10):
  my_list.append(i)

In this case, my_list would only contain even numbers between 0 and 9:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Likewise, there are a ton of different ways to add items to lists as well. If you’re interested in that sort of thing, I have an article on that.

Create a List with a List Comprehension

One of my favorite ways to create a list is using the list comprehension functionality. Essentially, it’s a compressed loop syntax that lets us generate simple lists. For instance, the first loop example could be written as a list comprehension as follows:

my_list = [i for i in range(10)]

Now, instead of manually appending items to a list, this expression handles all the heavy lifting. As a result, we can focus on modifying the expression to do fun things like scale all values in the range by 3:

my_list = [i * 3 for i in range(10)]

This expression will generate a list that looks like the following:

[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

While I’d be happy to dig into all the details, I already have a fun article and even a video which cover list comprehensions in depth. Check those resources out if you’re interested.

Performance

Now that we have a few solutions, let’s compare their performance. To do that, we’ll need to generate some strings:

static = """
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
loop = """
my_list = []
for i in range(10):
  my_list.append(i)
"""
comprehension = """
my_list = [i for i in range(10)]
"""

At this point, all we have to do is import the timeit library, so we can begin testing:

>>> import timeit
>>> min(timeit.repeat(stmt=static))
0.08311530000000289
>>> min(timeit.repeat(stmt=loop))
1.0872243000000026
>>> min(timeit.repeat(stmt=comprehension))
0.7429419999999993

And, there you have it! The quickest way to create a list is to declare it statically. That said, if you have to generate a list, the list comprehension seems to be the way to go.

Challenge

Now that you know how to create a list, I have a little challenge for you: create a list which contains the first 100 terms of the fibonacci sequence. For the purposes of this exercise, we’ll assume the first two terms are 1 and 1.

Feel free to use any solution from this article to generate your list. For example, you could compute the first 100 terms by hand and build up your list statically, Alternatively, you might choose to use a loop or even recursion to populate your list.

If you manage to generate the list using a list comprehension, let me know! I have no idea if that’s possible–at least not without doing some really nasty stuff. After all, you can’t access elements of the list as you’re building it, so it would be tough to track the previous values. That said, you may be able to take advantage of the new walrus operator or some outside state tracking mechanism.

At any rate, I’ll drop a solution in the comments. If you come up with something different, let me know!

A Little Recap

At this point, we’ve reached the end of the article. As always, I like to share a list of all the solutions for your perusal:

# Create a list statically
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Create a list with a loop
my_list = []
for i in range(0, 10, 2):
  my_list.append(i)
# Create a list with a list comprehension
my_list = [i for i in range(10)]

While you’re here, consider checking out some of these related articles:

Thanks for sticking around! I appreciate it.

Published on Web Code Geeks with permission by Jeremy Grifski, partner at our WCG program. See the original article here: How to Create a List in Python: Loops, Comprehensions, and More

Opinions expressed by Web Code Geeks contributors are their own.

Jeremy Grifski

Jeremy is the founder of The Renegade Coder, a software curriculum website launched in 2017. In addition, he is a PhD student with an interest in education and data visualization.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button