in
Operator
A list is a sequence of values. The values are not necessarily in any specific order, values may appear more than once, and values may be of different types, including other lists. Each value can be accessed individually and individual values in a list can be changed (i.e. a list is mutable). Lists are surrounded by square brackets "[]".
The simplest way to create a list is to assign values in square brackets to a variable. In general:
some_list = [v1, v2, ...]
Some examples:
Code | Description |
---|---|
red = [255, 0, 0] |
A list of 3 integers |
comparisons = ["Less Than", "Equal To", "Greater Than"] |
A list of 3 strings |
a_code = [65, "A"] |
A list of mixed value types |
empty = [] |
An empty list |
|
A list of variables and literals, equivalent to:[255,
'David', 'some string', 5.5] |
integers = list(range(0, 50, 5)) |
A list generated from a range, equivalent to:[0, 5, 10,
15, 20, 25, 30, 35, 40, 45] |
zeroes = [0] * 5 |
A list generated by multiplication, equivalent to:[0,
0, 0, 0, 0] |
(The term indexes == indices [the Latin plural of index] in this context.)
Individual elements of a list can be changed, as well as the entire list. Some examples:
Code | Result | Description |
---|---|---|
a = [1, 2, 3, 4] |
List variable creation | |
a |
[1, 2, 3, 4] |
No slicing used. |
a[1] |
2 |
Captures second element |
a[0] = 9 |
[9, 2, 3, 4] |
Changes contents of first element |
a[3] = 10 |
[9, 2, 3, 10] |
Changes contents of last element |
a[999] |
Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range |
Invalid index |
A list slice is accessed by assigning two indexes separated by a
":
". The values returned start with the first index up to,
but not including, the second index. Indexes that are too small, too
large, or left out default to 0 and the length of the list. Some examples:
Code | Result | Description |
---|---|---|
a = [1, 2, 3, 4] |
A list defined | |
a |
[1, 2, 3, 4] |
No slicing used. |
a[0:1] |
[1] |
Captures the first element only |
a[-100:100] |
[1, 2, 3, 4] |
Captures entire list |
a[1:3] |
[2, 3] |
Captures middle two elements |
a[:] |
[1, 2, 3, 4] |
Captures entire list, beginning and end slice indexes are set to
default of 0 and len(a)
|
a[2:] |
[3, 4] |
Captures all elements including and after index 2 |
a[:2] |
[1, 2] |
Captures all elements up to, but not including, index 2 |
a[-100:0] |
[] |
Captures nothing |
a[100:-100] |
[] |
Captures nothing |
Lists can be traversed - 'walked' through from one end to the other - in three ways. The following code shows how the contents of the list:
a = [9, 12, 24, 17]
can be traversed:
By index with a while
loop:
i = 0
n = len(a)
while i < n:
print(a[i])
i = i + 1
By index with a for
loop:
for i in range(n):
print(a[i])
By value with a for
loop:
for v in a:
print(v)
All three versions print the contents of a
as:
9 12 24 17
for i in a:
print(a[i])
i
is being treated as though it is an index, but it's not. It
is the same as the variable v
in the previous example - it is
actually a value in a
. What is being done here is the
equivalent of attempting to print:
a[9] a[12] a[24] a[17]
which isn't going to work, because a
doesn't have 9 values,
so the loop dies on the first iteration. We strongly recommend
that you use i
as a variable name for list iteration when it
is an index, but not when it is one of the values in the list.
Although you can use any variable name you like, using i
for
other than an index variable is potentially very confusing.
Lists can be passed into functions or returned from functions. The following sample function updates the contents of a list:
def double_list(values):
# Update the individual list values.
values[0] = values[0] * 2
values[1] = values[1] * 2
values[2] = values[2] * 2
# The function returns nothing as the contents
# of the list are changed by the function.
return
# The call:
from functions import double_list
double_list(some_list)
The contents of the list are updated inside the function, so the function does not have to return the list.
if a parameter to a Python function is an object (like a Python list), you
can update the contents of the object. The following shows the
difference between changing a parameter and changing the contents
of a parameter, where obj
is assumed to be a Python list:
def func(obj):
# attempts to change parameter - fails
obj = new_value
return
def func(obj):
# changes contents of parameter - works
obj[n] = new_value
obj.method() # such as .append(), .pop(), etc.
return
There are a number of list methods available which allow you to modify a list in place, i.e. to change the contents of the list directly. Because lists are mutable, they can be changed in place.
Method or Function | Purpose |
---|---|
value = a.pop()
|
Retrieves the last item in the list a and returns it
to value
- the item is removed from the list.
|
value = a.pop(i)
|
Retrieves the i th item in the list a and
returns it to value
- the item is removed from the list.
|
a.append(value) |
Appends value to the end of the list a .
Returns None .
|
a.reverse() |
Reverses the order of the items in the list a .
Returns None .
|
a.extend(b) |
Adds the contents of the list b to the end of the
list a . Returns None .
|
a.insert(i, value) |
Inserts value at position i in the list
a . Returns None .
|
Examples:
Code | Result | Description |
---|---|---|
a = [4, 5, 6] |
List variable creation | |
a.append(7) |
[4, 5, 6, 7] |
Appends a single value to end of list |
a.reverse() |
[7, 6, 5, 4] |
Contents of list are reversed |
|
[7, 6, 5, 4, 2, 3] |
Appends contents of one list to another |
a.insert(1, 12) |
[7, 12, 6, 5, 4, 2, 3] |
Inserts new element at index 1, remaining elements are moved to the right |
value = a.pop() |
3 [7, 12, 6, 5, 4, 2] |
Removes and returns last element in list, list is shortened |
value = a.pop(2) |
6 [7, 12, 5, 4, 2] |
Removes and returns element at index 2, list is shortened |
Lists can be sorted by calling the sort
method. Use with the
reverse
method to create a list of values in descending
order.
sort
returns None
.
Examples:
Code | Result | Description |
---|---|---|
a = [4, 7, 6, -2] |
List variable creation | |
a.sort() |
[-2, 4, 6, 7] |
Sorts contents of list in place (i.e. does not return a new list) |
a.reverse() |
[7, 6, 4, -2] |
Reverses contents of list in place (i.e. does not return a new list) |
x = a.sort() |
None [7, 6, 4, -2] |
When sorted in place, the sort method returns the
special Python value None |
in
Operator
The in
operator determines if a specific value is found in a
list or not, and returns True
or False
respectively. It is used as:
item in list
Examples:
Code | Result | Description |
---|---|---|
a = [4, 7, 6, -2] |
List variable creation | |
7 in a |
True |
Determines if value 7 is in the list a , does not
determine where (what index) it is
|
99 in a |
False |
99 is not an element of a |
|
True |
Puts result of in into a (boolean) variable
|
|
False |
Python allows mixed types in lists and operations |
Although two-dimensional (2-D) lists in Python do not have to be rectangular (i.e. each row does not have to have the same number of columns), we will assume that the lists we use in this lab are rectangular.
A 2-D list is really just a list of lists. All the same techniques that you use to manipulate one-dimensional (1-D) lists can be used to manipulate 2-D lists. To access a single element in a 1-D list use the same technique you used to access a single character in a string, that is the number of the element in square brackets after the name of the collection, as in this example:
some_list[5]
which accesses the element of some_list
with the index 5.
(Remember that list and string numbering starts at 0).
To access a single element of a 2-D list, give the row and column indexs in separate sets of square brackets, as in this example:
some_2d_list[2][5]
which accesses the element at row 2 and column 5 of some_2d_list
.
Both the row and column numbering start at 0.