
Lists
Lists in Python are versatile data structures that allow you to store a collection of items. It is created using square brackets []
or the list()
constructor.
Properties of Lists
- Lists can contain a mix of data types.
- Mutable: This means you can alter a list's elements after creation, such as adding, removing, or modifying items, without needing a new structure.
- Indexable: Elements can be accessed by their index.
- Iterable: Lists can be used in loops.
Example
The example below is a list named my_list
. It contains three integers, a string and a boolean value, showing that a list can hold a mix of data types.
my_list = [1, 2, 3, 'hello', True]
Indexing and Slicing Lists
Indexing
Indexing entails retrieving a particular element by its index. For example, to retrieve 'hello' from my_list
, you would use index 3. It's important to note that in Python, as with many programming languages, indexing starts from 0.
# Example of accesing the first element of my_listprint(my_list[0])
# Example of accessing the word 'hello' print(my_list[3])
Output:
1
hello
We can also use negative indexing which starts from the end, e.g. 'my_list[-1]'
accessses the last element.
# Access the last element of my_listprint(my_list[-1])
# Access the word 'hello' using negative indexingprint(my_list[-2])
Output:
True
hello
Slicing
Slicing refers to accessing a subset of a list. It's done using the colon :
symbol, e.g. my_list[0:3]
retrieves the first three elements. It's inclusive on the left and exclusive on the right.
Syntax: list[start : stop : step]
- start: The starting index (inclusive)
- stop: The ending index (exclusive)
- step: The step size (optional).
If the start or stop index is omitted, it defaults to the beginning or end of the list, respectively. For example, my_list[:3]
is equivalent to my_list[0:3]
, and my_list[2:]
is the same as my_list[2:4]
.
The step parameter specifies intervals, so my_list[::2]
accesses every second element in the list.
Example of slicing a list
# Create a new listlist_new = [10, 20, 30, 40, 50, 60]print('list_new: ', list_new)
Output:
list_new: [10, 20, 30, 40, 50, 60]
# 1. Get elements from index 0 to 2print(list_new[0:3])
# 2. Get elements from index 1 to 4print(list_new[1:5])
Output:
[10, 20, 30]
[20, 30, 40, 50]
# 3. Get every second element starting from index 0print('3. Get every second element starting from index 0:')print(list_new[::2])
print('---------------------')
# 4. Get every second element starting from index 1print('4. Get every second element starting from index 1:')print(list_new[1::2])
Output:
3. Get every second element starting from index 0:
[10, 30, 50]
---------------------
4. Get every second element starting from index 1:
[20, 40, 60]
Methods of Lists
Python lists offer a range of methods that extend their functionality. We'll delve into some of the most commonly used list methods.
These are list-specific methods, so you call them using list.method_name()
.
len()
Function
The len()
function returns the number of elements in a list.
# Create a new listlist_sample = [10, 20, 30, 40, 50, 60]
# get the number of elements in the listprint('the length of the list is', len(list_sample))
Output:
the length of the list is 6
append()
Function
The append()
function adds an item to the end of the list.
# create a listlist_sample=[1, 2, 3]print('list_sample:', list_sample)
# use append() method to add 4 to the end of the listlist_sample.append(4)print('list_sample after appending 4', list_sample)
Output:
list_sample: [1, 2, 3]
list_sample after appending 4 [1, 2, 3, 4]
After displaying list_sample
both before and after applying the append()
method, we observe that 4 has been appended to the end of list_sample
.
It's important to note that the append()
method for Python lists can only add one value at a time. You must use append()
multiple times to add multiple values. An alternative way of adding multiple values is using extend()
function.
extend()
Function
The extend()
function appends multiple values from a list or any iterable to the current list simultaneously.
# create two listsfirst_list = [1, 2, 3]second_list = [4, 5, 6]
print('first_list:', first_list)
# add second_list to my_listfirst_list.extend(second_list)print('first_list after adding the second list to it:', first_list)
Output:
first_list: [1, 2, 3]
first_list after adding the second list to it: [1, 2, 3, 4, 5, 6]
insert()
Function
The insert()
function inserts an item at a specified position.
Syntax: list.insert(index, value)
- index: the index of the target position
- value: the value you want to insert
# Create a listfirst_list = ['a', 'b', 'd']print('first_list:', first_list)
# Insert a value 'c' in between 'b' and 'd'first_list.insert(2, 'c')print("first_list after inserting 'c' at index 2:", first_list)
# Insert a value 'e' at the end of the listfirst_list.insert(4, 'e')print("first_list after inserting 'e' at index 4:", first_list)
# Inset a value 'aa' at the start of the listfirst_list.insert(0, 'aa')print("first_list after inserting 'aa' at index 0:", first_list)
Output:
first_list: ['a', 'b', 'd']
first_list after inserting 'c' at index 2: ['a', 'b', 'c', 'd']
first_list after inserting 'e' at index 4: ['a', 'b', 'c', 'd', 'e']
first_list after inserting 'aa' at index 0: ['aa', 'a', 'b', 'c', 'd', 'e']
index()
Function
The index
function returns the index of the first occurrence of an item.
Syntax: list.index(item)
- item: item is the target value you want to find the index of in the list.
# Create a listsample_list = ['hello', 'world', 'this', 'is', 'my', 'first', 'line', 'of', 'code', 'hello', 'again']
# Get the index of word 'first' in the listprint('index of word "first" in the list: ',sample_list.index('first'))
# Get the index of word 'hello' in the listprint('index of word "hello" in the list: ', sample_list.index('hello'))
Output:
index of word "first" in the list: 5
index of word "hello" in the list: 0
In the example, the word first is the 6th word in the list, making its index 5, as list indexing begins at 0.
Even though 'hello' appears twice in the list, the index()
method returns the index of its first occurrence.
count()
Function
The count()
function returns the number of occurrences of a specified value in a list.
# Create a listsample_list = ['hello', 'world', 'this', 'is', 'my', 'first', 'line', 'of', 'code', 'hello', 'again']
# Count how many times the word 'hello' appeared in the listsample_list.count('hello')
Output:
2
sort()
Function
The sort()
function sorts the list in ascending order by default.
Syntax: list.sort(reverse=False)
- reverse (optional): it's set to False by default, which sorts elements of a list in ascending order. If it's set to True, the list is sorted in descending order.
# Create a listsample_list = [4, 6, 2, 10, 1, 2, 8]
# Sort the sample_list ascendinglysample_list.sort()print('Sort sample_list in ascending order: ', sample_list)
# Sor the sample_list descendinglysample_list.sort(reverse=True)print('Sort sample_list in descending order by setting reverse = True: ', sample_list)
Output:
Sort sample_list in ascending order: [1, 2, 2, 4, 6, 8, 10]
Sort sample_list in descending order by setting reverse = True: [10, 8, 6, 4, 2, 2, 1]
reverse()
Function
The reverse()
function reverses the order of elements in a list.
# Create a listsample_list=[1, 2, 3]
# Reverse elements of sample_listsample_list.reverse()print(sample_list)
Output:
[3, 2, 1]
del()
Statement
The del()
statement is used to remove items from a list.
Deleting elements from a list
You can use del to remove elements from a list by specifying the index of the item you want to delete.
my_list = [1, 2, 3, 4, 5]
# Delete the element at index 2 (value 3)del my_list[2]print(my_list)
Output:
[1, 2, 4, 5]
Deleting slices from a list
You can also delete a slice of elements from a list using del.
my_list = [1, 2, 3, 4, 5]
# Delete elements from index 1 (inclusive) to index 3 (exclusive)del my_list[1:3]print(my_list)
Output:
[1, 4, 5]