List Basics
Introduction to Python Lists
Python lists are versatile and powerful data structures that allow you to store multiple items in a single variable. They are dynamic, ordered, and mutable, making them essential for many programming tasks.
Creating Lists
Lists can be created using several methods:
## Empty list
empty_list = []
## List with initial values
fruits = ['apple', 'banana', 'cherry']
## List constructor
numbers = list((1, 2, 3, 4, 5))
List Characteristics
Characteristic |
Description |
Ordered |
Elements maintain their insertion order |
Mutable |
Can be modified after creation |
Heterogeneous |
Can contain different data types |
Indexed |
Elements can be accessed by index |
Basic List Operations
Accessing Elements
fruits = ['apple', 'banana', 'cherry']
print(fruits[0]) ## First element
print(fruits[-1]) ## Last element
Slicing Lists
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[2:4]) ## Slice from index 2 to 3
print(numbers[:3]) ## First three elements
print(numbers[3:]) ## Elements from index 3 onwards
List Methods
flowchart TD
A[List Methods] --> B[append()]
A --> C[insert()]
A --> D[remove()]
A --> E[pop()]
A --> F[extend()]
Common List Methods
## Adding elements
fruits = ['apple', 'banana']
fruits.append('cherry') ## Add to end
fruits.insert(1, 'orange') ## Insert at specific index
## Removing elements
fruits.remove('banana') ## Remove specific element
last_fruit = fruits.pop() ## Remove and return last element
List Comprehensions
A powerful way to create lists concisely:
## Create a list of squares
squares = [x**2 for x in range(10)]
## Filtered list
even_squares = [x**2 for x in range(10) if x % 2 == 0]
Practical Considerations
When working with lists in LabEx Python environments, always consider:
- Memory efficiency
- Performance for large lists
- Choosing appropriate methods for your specific use case
By understanding these basics, you'll be well-equipped to manipulate lists effectively in your Python programming journey.