How to Build a List in Python
The problem...
You know what a list is. One variable, multiple values.
But knowing the concept isn't the same as knowing how to build one.
There are several ways to create a list in Python. Each one fits a different situation.
The most common way
You write the values directly, separated by commas, inside square brackets.
squad = ["Raven", "Wolf", "Ghost"]
This is called a list literal. You know the values upfront. You type them in. Done.
It works with any type:
scores = [98, 74, 85]
flags = [True, False, True]
mixed = ["Raven", 98, True]
Starting empty
Sometimes you don't have values yet. You need a list that starts empty and gets filled later.
roster = []
That's it. An empty list is valid. You'll add values to it as your program runs.
You can also use the built-in list() function to create an empty list:
roster = list()
Both do the same thing. [] is more common. You'll see both.
Building from a range
If you need a list of numbers in sequence, you don't type them by hand.
You use range() wrapped in list():
levels = list(range(1, 6))
print(levels)
Output → [1, 2, 3, 4, 5]
range(1, 6) generates numbers from 1 up to — but not including — 6. list() turns that into a list.
even = list(range(0, 11, 2))
print(even)
Output → [0, 2, 4, 6, 8, 10]
The third argument is the step. Here: start at 0, go up to 11, jump by 2.
Converting something else into a list
list() can also turn other things into a list. A string, for example:
letters = list("Bull")
print(letters)
Output → ['B', 'u', 'l', 'l']
Each character becomes a separate element. You won't use this every day, but it's good to know it exists.
The full picture
["a", "b", "c"]— list literal, values known upfront[]orlist()— empty list, values added laterlist(range(n))— list of numbers in sequencelist("text")— converts a string into a list of characters
Heads up!
range()alone is not a list — you needlist()to convert itlist(range(5))gives you[0, 1, 2, 3, 4]— it starts at 0 by default- Square brackets create a list — parentheses do not
- An empty list is not an error — it's a tool
The mindset shift
Stop thinking: "I'll figure out how to make the list when I need one."
Start thinking: "Which creation method fits what I'm trying to build?"
What you should understand now
- A list literal uses square brackets with values inside
- An empty list is created with
[]orlist() list(range())generates a list of numbers without typing them manuallylist()can convert other sequences into a list