List Basics
Introduction to Python Lists
In Python, lists are versatile and fundamental data structures that allow you to store multiple items in a single variable. They are ordered, mutable, and can contain elements of different types.
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 Operations
Accessing Elements
fruits = ['apple', 'banana', 'cherry']
## Indexing (zero-based)
first_fruit = fruits[0] ## 'apple'
last_fruit = fruits[-1] ## 'cherry'
## Slicing
subset = fruits[1:3] ## ['banana', 'cherry']
Modifying Lists
## Changing elements
fruits[1] = 'grape'
## Adding elements
fruits.append('orange')
fruits.insert(2, 'mango')
## Removing elements
fruits.remove('apple')
del fruits[1]
popped_fruit = fruits.pop()
List Methods
Method |
Description |
Example |
append() |
Adds an element to the end |
fruits.append('kiwi') |
extend() |
Adds multiple elements |
fruits.extend(['peach', 'plum']) |
insert() |
Adds element at specific index |
fruits.insert(2, 'berry') |
remove() |
Removes first matching element |
fruits.remove('banana') |
pop() |
Removes and returns last element |
last = fruits.pop() |
List Characteristics
graph TD
A[List Characteristics] --> B[Ordered]
A --> C[Mutable]
A --> D[Allow Duplicates]
A --> E[Heterogeneous]
Common List Operations
## Length of list
list_length = len(fruits)
## Checking membership
is_present = 'apple' in fruits
## Counting occurrences
count_apple = fruits.count('apple')
## Sorting
sorted_fruits = sorted(fruits)
fruits.sort()
Best Practices
- Use lists when you need an ordered collection of items
- Prefer list comprehensions for concise list creation
- Be mindful of performance with large lists
At LabEx, we recommend practicing these list operations to build strong Python programming skills.