In this section, we'll explore the power of lists in Python. We'll cover how to create, access, and modify lists to store and organize data efficiently.
A list in Python is an ordered collection of items. It's a versatile data structure that can store elements of different types, including numbers, strings, and even other lists. Lists are mutable, meaning you can change their contents after they are created.
We'll learn about the following topics:
Name | Type in Python | Description | Example |
---|---|---|---|
Lists | list | Comma-separated ordered sequence of objects in square brackets [ ]. | [10,'hello', 15.9] |
type([23, 98.3, 'hello'])
list
Lists in Python are created using square brackets []
. You can enclose the elements you want to include within the brackets, separated by commas.
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed_list = [10, "hello", 3.14, True]
len()
: Python's built-in len() function determines the total number of elements within a list's sequence.
a = ['one', 23, 98.3, 'hello']
len(a)
4
Elements in a list can be accessed individually by using square brackets and an index, just like accessing individual characters in a string. Both list indexing and string indexing follow a zero-based approach.
print(a)
['one', 23, 98.3, 'hello']
#Grab element at index 0
a[0]
'one'
#Grab index 1 and everything past it
a[1:]
[23, 98.3, 'hello']
#Grab everything UP TO index 2
a[:2]
['one', 23]
a[2:len(a)]
[98.3, 'hello']
String indexing and list indexing share numerous similarities. For instance, negative list indexing allows counting from the end of the list, mirroring its behavior in string indexing.
a[-1]
'hello'
a[:-3]
['one']
[start:stop:step]
a[::2]
['one', 98.3]
You can specify a negative step value as well, in which case Python steps backward through the list. In that case, the starting/first index should be greater than the ending/second index.
a
['one', 23, 98.3, 'hello']
a[4:0:-2]
['hello', 23]
This is a common paradigm for reversing a list.
a[::-1]
['hello', 98.3, 23, 'one']
a = ['one', 23, 98.3, 'hello']
b = [23, 98.3, 'one', 'hello']
a is b
False
a == b
False
a
['one', 23, 98.3, 'hello']
a[0] = 2
a
[2, 23, 98.3, 'hello']
You can insert multiple elements in place of a single element—just use a slice that denotes only one element.
a[0:1] = [3, 'Hello']
a
[3, 'Hello', 23, 98.3, 'hello']
Note that this is not the same as replacing the single element with a list.
a[0] = [7, 'World']
a
[[7, 'World'], 'Hello', 23, 98.3, 'hello']
You can also insert elements into a list without removing anything. Simply specify a slice of the form [n:n] (a zero-length slice) at the desired index.
c = [1, 2, 7, 8]
c[2:2] = [3, 4, 5, 6]
c
[1, 2, 3, 4, 5, 6, 7, 8]
a + ['new']
[[7, 'World'], 'Hello', 23, 98.3, 'hello', 'new']
Note: This doesn't actually change the original list!
a
[[7, 'World'], 'Hello', 23, 98.3, 'hello']
a[:2] + a[2:]
[[7, 'World'], 'Hello', 23, 98.3, 'hello']
a = a + ['new']
a
[[7, 'World'], 'Hello', 23, 98.3, 'hello', 'new']
We can use the multiplication symbol to create repetition.
a * 2
[[7, 'World'], 'Hello', 23, 98.3, 'hello', 'new', [7, 'World'], 'Hello', 23, 98.3, 'hello', 'new']
It’s not an accident that strings and lists behave so similarly. They are both special cases of a more general object type called an iterable, which you will encounter in more detail in the upcoming tutorial on definite iteration.
in
: Python also provides a membership operator that can be used with lists. The in operator returns True if the first operand is contained within the second, and False otherwise.'one' in a
False
not in
: Python also provides a membership operator that can be used with lists. The not in operator returns True if the first operand is not contained within the second, and False otherwise.'one' not in a
True
del
: A list item can be deleted with the del command.a
[[7, 'World'], 'Hello', 23, 98.3, 'hello', 'new']
del a[0:2]
a
[23, 98.3, 'hello', 'new']
Method | Description |
---|---|
append() | permanently add an item to the end of a list |
insert(index, m) | inserts object m into the list at the specified index |
pop(m(optional)) | By default pop takes off the last index, but you can also specify which index to pop off |
remove(m) | removes object m from the list |
reverse() | reverse order permanently |
sort() | in alphabetical order, but for numbers it will go ascending |
index() | find the index of the first occurrence of a specified element |
count(m,a(optional),b(optional)) | number of occurrences of m within the substring indicated by a and b |
a.append('2f')
a
[23, 98.3, 'hello', 'new', '2f']
a.insert(3, 6.5997)
a
[23, 98.3, 'hello', 6.5997, 'new', '2f']
a.pop()
'2f'
a
[23, 98.3, 'hello', 6.5997, 'new']
a.remove(6.5997)
a
[23, 98.3, 'hello', 'new']
.pop()
differs from .remove()
in two ways:
a.reverse()
.reverse()
is equivalent to List_name = list_name[::-1]
.
a
['new', 'hello', 98.3, 23]
b = ['a', 'v', 'm', 'c']
b.sort()
b
['a', 'c', 'm', 'v']
c = [4, 2, 5]
c.sort()
c
[2, 4, 5]
a.index(98.3)
2
d = [2, 'hello', 2, 3.5]
d.count(2)
2
A great feature of of Python data structures is that they support nesting. This means we can have data structures within data structures. For example: A list inside a list.
list_1 = [1,2,3]
list_2 = [4,5,6]
list_3 = [7,8,9]
#Make a list of lists to form a matrix
matrix = [list_1, list_2, list_3]
matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
len(matrix)
3
To access elements in a matrix, we use indexing twice: once for the overall matrix and again for the specific item within the list.
#Grab first item in matrix object
matrix[0]
[1, 2, 3]
#Grab first item of the first item in the matrix object
matrix[0][0]
1
matrix[0][1:3]
[2, 3]
nested = [[2,'hello',6.0], [59, 23.2]]
nested[1][0]
59
x = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']
x
['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']
The object structure that x references is diagrammed below: