5 Lists
5 Lists
CS100/CS101
Outline
●
List
●
List Examples, Nesting Lists
●
List Operations, MethodsList Slices, Length
●
Common Sequence Operations
●
Mutable Sequence Operations
●
Lists – References to objects
●
Copy Lists
●
Lists as Function Parameters
●
List Comprehensions
●
A5 – Encryption, Decryption, A6 – Raindrops
Lists
●
a compound data type
●
used to group together values from other datatypes
●
List: Comma-separated values (items) between square
brackets
●
Lists might contain items of different types, but usually
the items all have the same type.
●
Lists are mutable
List
>>>
>>> squares
squares == [1,
[1, 4,
4, 9,
9, 16,
16, 25]
25]
>>> squares
>>> squares
[1,
[1, 4,
4, 9,
9, 16,
16, 25]
25]
>>>
>>> squares[0] ## indexing
squares[0] indexing returns
returns the
the item
item
11
>>>
>>> squares[-1]
squares[-1]
25
25
>>>
>>> squares[-3:]
squares[-3:] ## slicing
slicing returns
returns aa new
new list
list
[9,
[9, 16,
16, 25]
25]
List
>>>
>>> squares
squares == [1,
[1, 4,
4, 9,
9, 16,
16, 25]
25]
>>>
>>> squares
squares
[1,
[1, 4,
4, 9,
9, 16,
16, 25]
25]
>>>
>>> squares[0]
squares[0] ## indexing
indexing returns
returns the
the item
item
11
>>>
>>> squares[-1]
squares[-1]
25
25
>>>
>>> squares[-3:]
squares[-3:] ## slicing
slicing returns
returns aa new
new list
list
[9,
[9, 16,
16, 25]
25]
>>>
>>> squares[:]
squares[:]
[1,
[1, 4,
4, 9,
9, 16,
16, 25]
25]
●
All slice operations return a new list
List Operations
>>>
>>> squares
squares ++ [36,
[36, 49,
49, 64,
64, 81,
81, 100]
100]
[1,
[1, 4,
4, 9,
9, 16,
16, 25,
25, 36,
36, 49,
49, 64,
64, 81,
81, 100]
100]
## lists
lists are
are mutable
mutable
>>>
>>> cubes
cubes == [1,
[1, 8,
8, 27,
27, 65,
65, 125]
125] ## something's
something's wrong
wrong here
here
>>>
>>> 44 **
** 33 ## the
the cube
cube of
of 44 is
is 64,
64, not
not 65!
65!
64
64
>>>
>>> cubes[3]
cubes[3] == 6464 ## replace
replace thethe wrong
wrong value
value
>>> cubes
>>> cubes
[1,
[1, 8,
8, 27,
27, 64,
64, 125]
125]
List Methods
>>>
>>> cubes.append(216)
cubes.append(216) ## add add the
the cube
cube of
of 66
>>>
>>> cubes.append(7
cubes.append(7 ** ** 3)
3) ## and
and the
the cube
cube ofof 77
>>>
>>> cubes
cubes
[1,
[1, 8,
8, 27,
27, 64,
64, 125,
125, 216,
216, 343]
343]
List Slices
>>>
>>> letters
letters == ['a',
['a', 'b',
'b', 'c',
'c', 'd',
'd', 'e',
'e', 'f',
'f', 'g']
'g']
>>> letters
>>> letters
['a',
['a', 'b',
'b', 'c',
'c', 'd',
'd', 'e',
'e', 'f',
'f', 'g']
'g']
>>> # replace some values
>>> # replace some values
>>>
>>> letters[2:5]
letters[2:5] == ['C',
['C', 'D',
'D', 'E']
'E']
>>> letters
>>> letters
['a',
['a', 'b',
'b', 'C',
'C', 'D',
'D', 'E',
'E', 'f',
'f', 'g']
'g']
>>> # now remove them
>>> # now remove them
>>>
>>> letters[2:5]
letters[2:5] == [] []
>>> letters
>>> letters
['a',
['a', 'b',
'b', 'f',
'f', 'g']
'g']
>>>
>>> ## clear
clear the
the list
list byby replacing
replacing all
all the
the elements
elements with
with an
an empty
empty list
list
>>> letters[:] =
>>> letters[:] = [] []
>>>
>>> letters
letters
[]
[]
List Length
>>>
>>> letters
letters == ['a',
['a', 'b',
'b', 'c',
'c', 'd']
'd']
>>> len(letters)
>>> len(letters)
44
Nesting Lists
>>>
>>> aa == ['a',
['a', 'b',
'b', 'c']
'c']
>>> n = [1, 2,
>>> n = [1, 2, 3] 3]
>>>
>>> xx == [a,
[a, n]
n]
>>> x
>>> x
[['a',
[['a', 'b',
'b', 'c'],
'c'], [1,
[1, 2,
2, 3]]
3]]
>>> x[0]
>>> x[0]
['a',
['a', 'b',
'b', 'c']
'c']
>>> x[0][1]
>>> x[0][1]
'b'
'b'
Common Sequence Operations
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s+t the concatenation of s and t
s * n or n * s equivalent to adding s to itself n times
s[i] ith item of s, origin 0
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
s.index(x[, i[, j]]) index of the first occurrence of x in s (at or after index i and before
index j)
s.count(<sub>, [<start> [, end]]) total number of occurrences of x in s
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
s.copy() creates a shallow copy of s (same as s[:])
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
s.copy() creates a shallow copy of s (same as s[:])
s.extend(t) or s += t extends s with the contents of t (for the most part the same as
s[len(s):len(s)] = t)
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
s.copy() creates a shallow copy of s (same as s[:])
s.extend(t) or s += t extends s with the contents of t (for the most part the same as
s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
s.copy() creates a shallow copy of s (same as s[:])
s.extend(t) or s += t extends s with the contents of t (for the most part the same as
s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
s.copy() creates a shallow copy of s (same as s[:])
s.extend(t) or s += t extends s with the contents of t (for the most part the same as
s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop() or s.pop(i) retrieves the item at i and also removes it from s
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
s.copy() creates a shallow copy of s (same as s[:])
s.extend(t) or s += t extends s with the contents of t (for the most part the same as
s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop() or s.pop(i) retrieves the item at i and also removes it from s
s.remove(x) remove the first item from s where s[i] is equal to x
Mutable Sequence Operations
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
s.copy() creates a shallow copy of s (same as s[:])
s.extend(t) or s += t extends s with the contents of t (for the most part the same as
s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop() or s.pop(i) retrieves the item at i and also removes it from s
s.remove(x) remove the first item from s where s[i] is equal to x
s.reverse() reverses the items of s in place
List Examples
>>>
>>> cubes_to_1000
cubes_to_1000 == [] []
>>> for number in range(11):
>>> for number in range(11):
...
... cubes_to_1000.append(number**3)
cubes_to_1000.append(number**3)
>>> cubes_to_1000
>>> cubes_to_1000
[0,
[0, 1,
1, 8,
8, 27,
27, 64,
64, 125,
125, 216,
216, 343,
343, 512,
512, 729,
729, 1000]
1000]
Lists – References to objects
>>>
>>> actual_names
actual_names == ["Tony",
["Tony", "Natasha",
"Natasha", "Thor",
"Thor", "Bruce"]
"Bruce"]
## Assigning
Assigning aa new
new variable
variable name
name does
does not
not make
make aa copy
copy of
of the
the container
container or
or its
its data.
data.
>>>
>>> same_list
same_list == actual_names
actual_names
## Altering
Altering the
the list
list via
via the
the new
new name
name is
is the
the same
same as
as altering
altering the
the list
list via
via the
the old
old name.
name.
>>> same_list.append("Clarke")
>>> same_list.append("Clarke")
>>>
>>> same_list
same_list
["Tony",
["Tony", "Natasha",
"Natasha", "Thor",
"Thor", "Bruce",
"Bruce", "Clarke"]
"Clarke"]
>>> actual_names
>>> actual_names
["Tony",
["Tony", "Natasha",
"Natasha", "Thor",
"Thor", "Bruce",
"Bruce", "Clarke"]
"Clarke"]
Lists – References to objects
>>>
>>> actual_names
actual_names == ["Tony",
["Tony", "Natasha",
"Natasha", "Thor",
"Thor", "Bruce"]
"Bruce"]
## Assigning
Assigning aa new
new variable
variable name
name does
does not
not make
make aa copy
copy of
of the
the container
container or
or its
its
data.
data.
>>>
>>> same_list
same_list == actual_names
actual_names
## Altering
Altering the
the list
list via
via the
the new
new name
name is
is the
the same
same as
as altering
altering the
the list
list via
via
the old name.
the old name.
>>>
>>> same_list.append("Clarke")
same_list.append("Clarke")
>>> same_list
>>> same_list
["Tony",
["Tony", "Natasha",
"Natasha", "Thor",
"Thor", "Bruce",
"Bruce", "Clarke"]
"Clarke"]
>>> actual_names
>>> actual_names
["Tony",
["Tony", "Natasha",
"Natasha", "Thor",
"Thor", "Bruce",
"Bruce", "Clarke"]
"Clarke"]
## Likewise,
Likewise, altering
altering the
the data
data in
in the
the list
list via
via the
the original
original name
name will
will also
also
alter the data under the new name.
alter the data under the new name.
>>>
>>> actual_names[0]
actual_names[0] == "Wanda"
"Wanda"
>>> same_list
>>> same_list
['Wanda',
['Wanda', 'Natasha',
'Natasha', 'Thor',
'Thor', 'Bruce',
'Bruce', 'Clarke']
'Clarke']
Copy Lists
## If
If you
you copy
copy the
the list,
list, there
there will
will be
be two
two separate
separate list
list objects
objects which
which can
can be
be
changed
changed independently.
independently.
>>>
>>> copied_list
copied_list == actual_names.copy()
actual_names.copy()
>>>
>>> copied_list[0]
copied_list[0] == "Tony"
"Tony"
>>>
>>> actual_names
actual_names
['Wanda',
['Wanda', 'Natasha',
'Natasha', 'Thor',
'Thor', 'Bruce',
'Bruce', 'Clarke']
'Clarke']
>>>
>>> copied_list
copied_list
["Tony",
["Tony", "Natasha",
"Natasha", "Thor",
"Thor", "Bruce",
"Bruce", "Clarke"]
"Clarke"]
Lists as Function Parameters
def
def solve(a):
solve(a): def solve(a):
print(a)
print(a) print(a, id(a))
##
## a=[1,7,3] # try with and
a=[1,7,3] # try with and without
without this
this statement
statement
a[2]=100
## a=[1,7,3]
a[2]=100 a[2]=100
print(a)
print(a)
return print(a, id(a))
return
return
a=[2,4,6]
a=[2,4,6] a=[2,4,6]
print(a)
print(a) print(a, id(a))
solve(a)
solve(a) solve(a)
print(a)
print(a) print(a, id(a))
List Comprehension
List Comprehensions
●
List comprehensions provide a concise way to
create lists
●
make new lists where each element is the result of
some operations applied to each member of another
sequence or iterable
●
create a subsequence of list elements that satisfy a
certain condition.
List
>>>
>>> squares
squares == [][]
>>> for x in range(10):
>>> for x in range(10):
...
... squares.append(x**2)
squares.append(x**2)
...
...
>>>
>>> squares
squares
[0,
[0, 1,
1, 4,
4, 9,
9, 16,
16, 25,
25, 36,
36, 49,
49, 64,
64, 81]
81]
List
>>>
>>> squares
squares == [][]
>>> for x in range(10):
>>> for x in range(10):
...
... squares.append(x**2)
squares.append(x**2)
...
...
>>>
>>> squares
squares
[0,
[0, 1,
1, 4,
4, 9,
9, 16,
16, 25,
25, 36,
36, 49,
49, 64,
64, 81]
81]
>>>
>>> squares
squares == [x**2
[x**2 for
for xx in
in range(10)]
range(10)]
Combining 2 lists
>>>
>>> [(x,
[(x, y)
y) for
for xx in
in [1,2,3]
[1,2,3] for
for yy in
in [3,1,4]
[3,1,4] if
if xx !=
!= y]
y]
## is
is same
same as
as
>>>
>>> combs
combs == [][]
>>>
>>> for
for xx in
in [1,2,3]:
[1,2,3]:
...
... for
for yy inin [3,1,4]:
[3,1,4]:
...
... if
if xx !=
!= y:
y:
...
... combs.append((x,
combs.append((x, y)) y))
...
...
>>>
>>> combs
combs
[(1,
[(1, 3),
3), (1,
(1, 4),
4), (2,
(2, 3),
3), (2,
(2, 1),
1), (2,
(2, 4),
4), (3,
(3, 1),
1), (3,
(3, 4)]
4)]
more listcomps
>>>
>>> vec
vec == [-4,
[-4, -2,
-2, 0,
0, 2,
2, 4]
4]
>>>
>>> ## create
create aa new
new list
list with
with the
the values
values doubled
doubled
>>>
>>> [x*2
[x*2 for
for xx in
in vec]
vec]
[-8,
[-8, -4,
-4, 0,0, 4,
4, 8]
8]
>>>
>>> ## filter
filter the
the list
list to
to exclude
exclude negative
negative numbers
numbers
>>>
>>> [x
[x for
for xx in
in vec
vec if
if xx >=
>= 0]
0]
[0,
[0, 2,
2, 4]
4]
>>>
>>> ## apply
apply aa function
function to to all
all the
the elements
elements
>>>
>>> [abs(x)
[abs(x) forfor xx in
in vec]
vec]
[4,
[4, 2,
2, 0,
0, 2,
2, 4]
4]
more listcomps
>>>
>>> ## call
call aa method
method on
on each
each element
element
>>>
>>> freshfruit
freshfruit == ['[' banana',
banana', '' loganberry
loganberry ',
', 'passion
'passion fruit
fruit
']
']
>>>
>>> [weapon.strip()
[weapon.strip() for for weapon
weapon in
in freshfruit]
freshfruit]
['banana',
['banana', 'loganberry',
'loganberry', 'passion
'passion fruit']
fruit']
>>>
>>> ## create
create aa list
list of
of 2-tuples
2-tuples like
like (number,
(number, square)
square)
>>>
>>> [(x,
[(x, x**2)
x**2) for
for xx in
in range(6)]
range(6)]
[(0,
[(0, 0),
0), (1,
(1, 1),
1), (2,
(2, 4),
4), (3,
(3, 9),
9), (4,
(4, 16),
16), (5,
(5, 25)]
25)]
more listcomps
>>>
>>> ## the
the tuple
tuple must
must be
be parenthesized,
parenthesized, otherwise
otherwise an
an error
error is
is
raised
raised
>>>
>>> [x,
[x, x**2
x**2 for
for xx in
in range(6)]
range(6)]
File
File "<stdin>",
"<stdin>", line
line 1,1, in
in <module>
<module>
[x,
[x, x**2
x**2 for
for xx in
in range(6)]
range(6)]
^^
SyntaxError:
SyntaxError: invalid
invalid syntax
syntax
more listcomps
>>>
>>> ## flatten
flatten aa list
list using
using aa listcomp
listcomp with
with two
two 'for'
'for'
>>>
>>> vec
vec == [[1,2,3],
[[1,2,3], [4,5,6],
[4,5,6], [7,8,9]]
[7,8,9]]
>>>
>>> [num
[num for
for elem
elem in
in vec
vec for
for num
num in
in elem]
elem]
[1,
[1, 2,
2, 3,
3, 4,
4, 5,
5, 6,
6, 7,
7, 8,
8, 9]
9]
more listcomps
>>>
>>> from
from math
math import
import pi
pi
>>>
>>> [str(round(pi,
[str(round(pi, i))
i)) for
for ii in
in range(1,
range(1, 6)]
6)]
['3.1',
['3.1', '3.14',
'3.14', '3.142',
'3.142', '3.1416',
'3.1416', '3.14159']
'3.14159']
Nested listcomps
●
The initial expression in a list comprehension
can be any arbitrary expression, including
another list comprehension.
Nested listcomps
>>>
>>> matrix
matrix == [[
...
... [1,
[1, 2,
2, 3,
3, 4],
4],
...
... [5,
[5, 6,
6, 7,
7, 8],
8],
...
... [9,
[9, 10,
10, 11,
11, 12],
12],
...
... ]]
>>>
>>> [[row[i]
[[row[i] forfor row
row in
in matrix]
matrix] for
for ii in
in range(4)]
range(4)]
[[1,
[[1, 5,
5, 9],
9], [2,
[2, 6,
6, 10],
10], [3,
[3, 7,
7, 11],
11], [4,
[4, 8,
8, 12]]
12]]
## same
same as
as
>>>
>>> transposed
transposed == [] []
>>>
>>> for
for ii in
in range(4):
range(4):
...
... transposed.append([row[i]
transposed.append([row[i] for for row
row in
in matrix])
matrix])
...
...
A5 – Encryption, Decryption
A5 – Encryption, Decryption
●
Implement a Substitution Cipher
●
Substitution cipher replaces plaintext with an
identical length ciphertext
●
Ciphers render text less readable while still
allowing easy deciphering
print(convert(34))
print(convert(34))
rim
rim jhim
jhim
print(convert(210))
print(convert(210))
rim
rim jhim
jhim jal
jal tarang
tarang baadal
baadal chalte
chalte hain
hain
A6 – Raindrops
Summary
●
List
●
List Examples, Nesting Lists
●
List Operations, MethodsList Slices, Length
●
Common Sequence Operations
●
Mutable Sequence Operations
●
Lists – References to objects
●
Copy Lists
●
Lists as Function Parameters
●
List Comprehensions
●
A5 – Encryption, Decryption, A6 – Raindrops