4.1 Lists: Creation, Indexing, Slicing, and Operations
Lists are one of the most versatile and commonly used data structures in Python. A list is an ordered collection of items, which can be of different types (integers, floats, strings, or even other lists). Lists are mutable, meaning their elements can be changed, and they offer many built-in operations to work with their elements efficiently.
In this section, we’ll explore how to create lists, access and modify their elements using indexing and slicing, and perform various operations on lists.
4.1.1 Creating Lists
A list is created by placing elements inside square brackets []
, separated by commas. You can store elements of any type, including other lists.
Syntax:
my_list = [element1, element2, element3, ...]
Examples:
An empty list:
empty_list = []
A list of lists (nested list):
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
A mixed-type list:
mixed_list = [1, "hello", 3.14, True]
A list of strings:
fruits = ["apple", "banana", "cherry"]
A list of integers:
numbers = [1, 2, 3, 4, 5]
4.1.2 Indexing Lists
List elements can be accessed by their index. Python uses zero-based indexing, meaning the first element of a list is at index 0
. You can also use negative indexing to access elements from the end of the list (-1
is the last element, -2
is the second-to-last, and so on).
Syntax:
list_name[index]
Examples:
Accessing elements in a nested list:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2]) # Output: 6 (third element of the second list)
Using negative indexing:
print(fruits[-1]) # Output: cherry (last element)
print(fruits[-2]) # Output: banana (second-to-last element)
Accessing the first and third element of a list:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
4.1.3 Slicing Lists
Slicing allows you to access a range of elements in a list. The syntax for slicing is list[start:end]
, where start
is the index of the first element to include, and end
is the index of the element not to include. You can also specify a step size using the syntax list[start:end:step]
.
Syntax:
list_name[start:end]
list_name[start:end:step]
Examples:
Slicing with negative indices:
print(fruits[-4:-1]) # Output: ['banana', 'cherry', 'date'] (slice from second to last)
Using a step size:
print(fruits[::2]) # Output: ['apple', 'cherry', 'fig'] (every second element)
Omitting start
or end
:
print(fruits[:3]) # Output: ['apple', 'banana', 'cherry'] (from start to index 2)
print(fruits[2:]) # Output: ['cherry', 'date', 'fig'] (from index 2 to end)
Slicing from index 1
to 3
:
fruits = ["apple", "banana", "cherry", "date", "fig"]
print(fruits[1:4]) # Output: ['banana', 'cherry', 'date']
4.1.4 List Operations
Python provides several built-in operations for working with lists, including concatenation, repetition, membership testing, and more.
4.1.4.1 Concatenation
You can concatenate two lists using the +
operator, which creates a new list by combining the two lists.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
4.1.4.2 Repetition
You can repeat a list multiple times using the *
operator.
Example:
repeated_list = [1, 2, 3] * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
4.1.4.3 Membership Testing
You can check whether an item exists in a list using the in
and not in
operators.
Example:
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # Output: True
print("grape" not in fruits) # Output: True
4.1.4.4 List Length
You can determine the number of elements in a list using the len()
function.
Example:
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
4.1.4.5 List Modification
Since lists are mutable, you can modify their elements, add new elements, or remove elements.
- Adding Elements:
- Removing Elements:
clear()
: Removes all elements from the list.
fruits.clear()
print(fruits) # Output: []
pop()
: Removes and returns the element at a specific index (default is the last element).
last_fruit = fruits.pop()
print(last_fruit) # Output: grape
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'date', 'fig']
remove()
: Removes the first occurrence of a value.
fruits.remove("avocado")
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'date', 'fig', 'grape']
insert()
: Inserts an element at a specific position.
fruits.insert(1, "avocado")
print(fruits) # Output: ['apple', 'avocado', 'blueberry', 'cherry', 'date', 'fig', 'grape']
extend()
: Adds all elements from another list (or any iterable) to the end of the list.
fruits.extend(["fig", "grape"])
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'date', 'fig', 'grape']
append()
: Adds a single element to the end of the list.
fruits.append("date")
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'date']
Modifying Elements:
Example:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
4.1.4.6 Sorting and Reversing
You can sort or reverse the elements of a list using the sort()
and reverse()
methods.
Reversing:
Example:
numbers.reverse()
print(numbers) # Output: [9, 4, 2, 1]
Sorting:
Example:
numbers = [4, 2, 9, 1]
numbers.sort()
print(numbers) # Output: [1, 2, 4, 9]
4.1.5 List Comprehensions
List comprehensions provide a concise way to create lists by applying an expression to each element of an iterable. They are commonly used to transform or filter lists in a single line of code.
Syntax:
new_list = [expression for item in iterable if condition]
Examples:
Create a list of squares:
squares = [x
**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
2. Filter even numbers from a list:
```python
numbers = [1, 2, 3, 4, 5, 6]
evens = [x for x in numbers if x % 2 == 0]
print(evens) # Output: [2, 4, 6]
4.1.6 Summary
- Lists are mutable, ordered collections of elements that can hold items of any data type.
- Indexing allows you to access individual elements in a list, while slicing allows you to retrieve ranges of elements.
- You can perform various operations on lists, such as concatenation, repetition, and membership testing.
- Lists can be modified by adding, changing, or removing elements using methods like
append()
,remove()
, andpop()
. - List comprehensions provide a compact way to generate new lists from existing ones, often applying transformations or filtering elements.
Lists are one of Python's most powerful and flexible data structures. Mastering them will help you handle collections of data efficiently and perform various transformations and manipulations.