Skip to main content

How to Create a List in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A list keeps several values in order, in one variable: colors, names, prices. In Python you write it with square brackets, and you can add, read and change its items at any time.

Syntax​

Syntax
<list> = [<item>, <item>, <item>]
<list>.append(<item>)
<list>[<index>]
PartWhat it does
[ ... ]Creates a list. [] on its own is an empty one.
.append(<item>)Adds an item at the end.
<list>[<index>]Reads an item. 0 is the first, -1 the last.

The Python documentation lists the ways to build a list, the first two being "Using a pair of square brackets to denote the empty list: []" and "Using square brackets, separating items with commas: [a], [a, b, c]".

The Example​

The example starts a list of three colors, appends a fourth, and prints the list and its first and last items.

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2.

Step 1: Write the List​

Create a file named main.py:

main.py, which creates colors with red, green and blue, appends yellow, prints colors and prints colors[0] and colors[-1].

main.py
colors = ["red", "green", "blue"]

colors.append("yellow")

print(colors)
print(colors[0], colors[-1])

Step 2: Run It​

Terminal
uv run python main.py
Output
['red', 'green', 'blue', 'yellow']
red yellow

A zsh terminal where uv run python main.py prints the list red, green, blue, yellow and then red yellow.

append changed the list itself, so it now has four colors. colors[0] is the first and colors[-1] the last. The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Counting from 1, as in colors[3] for the third colorYou get the fourth item, or an error past the endThe third item is colors[2]
Reading past the endIndexError: list index out of rangeCheck len(colors) first
Writing colors = colors.append("yellow")append returns None, so colors becomes NoneCall colors.append(...) on its own line

Troubleshooting​

SymptomLikely causeFix
IndexError: list index out of rangeThe index is bigger than the listPrint the list and its length
A list is suddenly NoneThe result of append was assignedDon't assign the result of append

FAQ​

Can a list hold different types?​

Yes, such as ["Ada", 36, True], though lists usually hold one kind of thing.

How do I check whether an item is in a list?​

Use in: "green" in colors is True.

Conclusion​

Square brackets create a list, append adds to the end, and list[0] and list[-1] read the first and last items.

Additional Resources​