Welcome back! In this section, we'll dive into one of Python's most fundamental and versatile data structures: lists. Think of a list as a container where you can store a collection of items. What makes lists special is that they are 'ordered' and 'mutable'.
'Ordered' means that the items in a list have a specific sequence, and this sequence will not change unless you explicitly modify it. Each item in the list has an 'index', which is its position. Indices in Python start from 0 for the first item, 1 for the second, and so on.
'Mutable' means that you can change, add, or remove items from a list after it has been created. This flexibility is incredibly powerful for managing data dynamically.
Let's see how to create a list:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = ["hello", 10, True, 3.14]
empty_list = []As you can see, lists can hold items of the same data type (like fruits and numbers) or different data types (like mixed_list). An empty list can also be created.
Accessing items in a list is done using their index. You use square brackets [] with the index number inside.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: bananaPython also supports negative indexing, where -1 refers to the last item, -2 to the second-to-last, and so on. This is a convenient way to access elements from the end of the list.
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # Output: cherry
print(fruits[-2]) # Output: bananaWhat happens if you try to access an index that doesn't exist? You'll get an IndexError.