List Basics in Python
What is a Python List?
In Python, a list is a versatile and fundamental data structure that allows you to store multiple items in a single variable. Lists are ordered, mutable, and can contain elements of different types. They are defined using square brackets []
and provide a flexible way to manage collections of data.
Creating Lists
There are multiple ways to create lists in Python:
## Empty list
empty_list = []
## List with initial elements
fruits = ['apple', 'banana', 'cherry']
## List with mixed data types
mixed_list = [1, 'hello', 3.14, True]
## List constructor
numbers = list(range(1, 6))
List Characteristics
Lists in Python have several key characteristics:
Characteristic |
Description |
Ordered |
Elements maintain their insertion order |
Mutable |
Can be modified after creation |
Indexed |
Elements can be accessed by their position |
Duplicates |
Allow duplicate elements |
List Operations
Accessing Elements
fruits = ['apple', 'banana', 'cherry']
print(fruits[0]) ## First element
print(fruits[-1]) ## Last element
Modifying Lists
## Adding elements
fruits.append('orange')
fruits.insert(1, 'grape')
## Removing elements
fruits.remove('banana')
del fruits[1]
List Comprehensions
List comprehensions provide a concise way to create lists:
## Create a list of squares
squares = [x**2 for x in range(1, 6)]
print(squares) ## [1, 4, 9, 16, 25]
Nested Lists
Lists can contain other lists, creating multi-dimensional structures:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
When to Use Lists
Lists are ideal for:
- Storing collections of similar or related items
- Maintaining order of elements
- Dynamic collections that may change
- Implementing stacks, queues, and other data structures
At LabEx, we recommend understanding lists as a fundamental skill for Python programming, as they form the basis of many advanced data manipulation techniques.