List Basics
Introduction to Python Lists
In Python, a list is a versatile and fundamental data structure that allows you to store multiple items in a single collection. Lists are ordered, mutable, and can contain elements of different types.
Creating Lists
Lists can be created using square brackets []
or the list()
constructor:
## Creating lists
fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, 'hello', 3.14, True]
## Using list() constructor
empty_list = list()
List Characteristics
Characteristic |
Description |
Ordered |
Elements maintain their insertion order |
Mutable |
Can be modified after creation |
Indexed |
Elements can be accessed by their position |
Heterogeneous |
Can contain different data types |
Basic List Operations
Accessing Elements
fruits = ['apple', 'banana', 'cherry']
## Positive indexing
print(fruits[0]) ## Output: apple
## Negative indexing
print(fruits[-1]) ## Output: cherry
Modifying Lists
## Changing elements
fruits[1] = 'grape'
## Adding elements
fruits.append('orange')
## Removing elements
fruits.remove('apple')
List Slicing
numbers = [0, 1, 2, 3, 4, 5]
## Slicing syntax: list[start:end:step]
subset = numbers[1:4] ## [1, 2, 3]
reversed_subset = numbers[::-1] ## [5, 4, 3, 2, 1, 0]
List Methods
flowchart TD
A[List Methods] --> B[append()]
A --> C[extend()]
A --> D[insert()]
A --> E[remove()]
A --> F[pop()]
A --> G[clear()]
A --> H[index()]
A --> I[count()]
A --> J[sort()]
A --> K[reverse()]
Common Use Cases
Lists are widely used in Python for:
- Storing collections of items
- Implementing stacks and queues
- Handling dynamic data
- Performing iterations and transformations
By understanding these basics, you'll be well-prepared to work with lists in Python. In the next section, we'll explore reverse iteration techniques that LabEx recommends for efficient list manipulation.