Lists
Programming Languages · Python Control Flow & Lists · 12 min
Keep many values in one list, then add, remove, slice and sort them.
Making a list
A list holds several values in order. Write them inside square brackets, separated by commas:
colors = ["red", "green", "blue"]
print(colors)
One variable, many values. Lists can hold text, numbers or a mix.
Create a list
fruitswith"apple","banana"and"cherry".Print
fruits.
Picking items by index
Just like letters in a string, list items have an index starting at 0. Negative numbers count from the end:
pets = ["cat", "dog", "fish"]
print(pets[0]) # cat
print(pets[-1]) # fish, the last one
Print the first item of
fruits.Print the last item using
-1.
Adding and removing
Lists can grow and shrink:
pets = ["cat"]
pets.append("dog") # add to the end
pets.insert(0, "fish") # add at index 0
pets.remove("cat") # take out "cat"
print(pets) # ['fish', 'dog']
Add
"cherry"to the end offruitswith.append().Put
"kiwi"at the front with.insert().Take out
"banana"with.remove().
Length and slices
len() works on lists too: it counts the items. Slices also work the same way as with strings:
nums = [10, 20, 30, 40]
print(len(nums)) # 4
print(nums[1:3]) # [20, 30]
Remember, the slice stops before the second index.
Print how many items are in
numbers.Print the slice
numbers[1:4].
Sorting
.sort() puts a list in order, smallest first (or A to Z for text). It changes the list itself.
ages = [30, 9, 18]
ages.sort()
print(ages) # [9, 18, 30]
Want biggest first? Use ages.sort(reverse=True).
Sort
scores, then print it.Print the highest score using
scores[-1].
Put it together: a shopping list
Update a shopping list: add two things, cross one off, put it in A to Z order and count what's left.
Append
"bread"and"apples", then remove"eggs".Sort
itemsand print it.Print
3 items, usinglen(items)for the number.
More in Python Control Flow & Lists
Previous: Conditionals · Next: Loops