Python Lists: Create, Print and Count Items
What Is a List in Python?
A list stores many values in one variable. You write the values inside square brackets [ ], with a comma between them.
Think of it like a shopping list on paper: one sheet, many items, in the order you wrote them down.
fruits = ["apple", "banana", "mango"]
print(fruits)['apple', 'banana', 'mango']
The rules
- A square bracket
[starts the list, and]ends it. - A comma
,goes between two values. - Each value in a list is called an item (some books say element).
- A list keeps the order you wrote. Python never shuffles it by itself.
Python prints a list the way you would type it, brackets and commas included. Notice that the strings now show single quotes '. That's only how Python shows text inside a list. Single and double quotes mean the same thing (chapter 5).
Why not many variables?
Without a list, three friends need three variables:
friend1 = "Sunny"
friend2 = "Rocky"
friend3 = "Lucky"
print(friend1, friend2, friend3)Sunny Rocky Lucky
With a list, one name holds them all:
friends = ["Sunny", "Rocky", "Lucky"]
print(friends)['Sunny', 'Rocky', 'Lucky']
A fourth friend? Add one more item, not one more variable. And in chapter 10, a for loop will visit every item of a list for you.
Common beginner doubt: a missing comma
colors = ["red" "blue"]
print(colors)['redblue']
No error, but only one item! Two strings written side by side are glued into one string. Python saw "redblue". Always check the commas between your items.
A list holds many values, in order, inside square brackets.