In Python, a list is a mutable, ordered collection of items. Lists can hold a variety of data types (including other lists) and allow for easy manipulation and access to their elements.
Creating a List
You can create a list by placing items inside square brackets []
, separated by commas.
# Empty list
empty_list = []
# List of integers
numbers_list = [1, 2, 3, 4, 5]
# List of mixed data types
mixed_list = [1, "Hello", 3.14, True]
Accessing List Elements
You can access elements in a list using indexing. Python uses zero-based indexing, so the first element has an index of 0
.
numbers = [20, 30, 40, 50]
print(numbers[0]) # Output: 20
print(numbers[2]) # Output: 40
# Negative indexing accesses elements from the end of the list
print(numbers[-1]) # Output: 50 (last element)
Modifying a List
Since lists are mutable, you can modify, add, or remove elements after the list is created.
Changing elements:
numbers[1] = 35
print(numbers) # Output: [20, 35, 40, 50]