You know how to store one value in a variable, like
age = 25. But what if you need to track three grades or five friends? You do not want ten separate variables. A list solves this by holding multiple items inside one ordered collection.You create a list using square brackets
[]. Inside, you place your values separated by commas. The order matters because Python remembers the position of each item.fruits = ['apple', 'banana', 'cherry']
print(fruits)
# Output: ['apple', 'banana', 'cherry']The variable
fruits now holds three strings. When you print it, Python shows the entire collection in one line with brackets.Indexing
To get a specific item out of a list, you use indexing. Python counts positions starting at
0, not 1. The first item is index 0, the second is 1.colors = ['red', 'green', 'blue']
print(colors[0]) # red
print(colors[2]) # blue
print(colors[-1]) # also blue (last item)colors[0] grabs the first string. colors[-1] is a handy shortcut for the last item, which helps when you do not know how long the list is.Length and Membership
You often need to know how many items are in a list. Use
len() for this count. You can also check if a value exists inside the list using the keyword in.nums = [10, 20, 30]
print(len(nums)) # 3
print(20 in nums) # True
print(99 in nums) # Falselen() returns an integer count. The in check returns a boolean: True if found, or False otherwise.Modifying Lists
Lists are mutable, meaning you can change them after creation. The
.append() method adds a new item to the very end of the list.todo = ['eat', 'sleep']
todo.append('code') # adds to end
print(todo) # ['eat', 'sleep', 'code']You can also remove items.
.remove(item) deletes the first occurrence of a specific value. .pop() removes the last item and hands it back to you; give it a position, like .pop(0), to take that item instead.todo.remove('eat') # removes 'eat'
last_item = todo.pop() # removes last item
print(last_item) # code