Lists: Ordered, Mutable Sequences
Lists are the most versatile and commonly used data structure in Python. A list is an ordered collection of items, and it is mutable (meaning you can change its contents after creation).
Lists are defined using square brackets [], with items separated by commas.
Creating Lists
Lists can hold items of different data types (though often they hold items of the same type).
python
List of strings
fruits = ['apple', 'banana', 'cherry']
List of mixed types
mixed_list = [1, 'hello', 3.14, True]
Empty list
empty_list = []
Accessing List Elements
Lists use zero-based indexing and slicing, just like strings.
python print(fruits[0]) # Output: apple print(fruits[-1]) # Output: cherry
Slicing
subset = fruits[1:3] print(subset) # Output: ['banana', 'cherry']
Mutability: Changing Elements
Because lists are mutable, you can change individual elements using their index.
python colors = ['red', 'blue', 'green'] colors[1] = 'yellow' # Change the item at index 1 print(colors) # Output: ['red', 'yellow', 'green']