55284A - Introduction to Python _ Chapter5
55284A - Introduction to Python _ Chapter5
Topics Covered
Lists. T
his
doc
Tuples. um
en
tb
elo
n
Ranges. No jagta gs to
un p NI
au nilka LK
t
Dictionaries. h o riz
n t @ ANT
ed re ES
co diff.c HW
pie o AR
Sets. sa m JA
llo GT
we AP
d! .
The *args and **kwargs parameters.
I did not like this iteration of one idea--this strange recurrence of one image, and I grew nervous as
bedtime approached and the hour of the vision drew near.
Th
– Jane isEyre, Charlotte Bronte
do
cu
me
nt
be
lon
Introduction No un agtapn gs to N
j
au il ILK
tho kant
riz @ ANT
ed red E
iff. SHW
co their
Iterables are objects that can return pie c
members
o AR one at a time. The iterables we will cover in this lesson are lists,
sa m JA
tuples, ranges, dictionaries, and sets. llo GT
we AP
d! .
Definitions
Here are some quick definitions to provide an overview of the different types of objects we will be covering in this
lesson. Don’tT worry if the meanings aren’t entirely clear now. They will be when you finish the lesson.
his
do
cu
me
1. Sequences are iterables nt
be that can return members based on their position within the iterable. Examples of
lon
sequences are No agta lists,
strings,
j gs tuples, and ranges.
un pn to NI
au il LK
tho kant sequences
2. Lists are mutable (changeable) riz @ ANT similar to arrays in other programming languages.
ed red ES
co if H
3. Tuples are immutable sequences. pie f.com WAR
sa JA
llo GT
we A
4. Ranges are immutable sequences of numbers often Pused d ! . in for loops.
5. Dictionaries are mappings that use arbitrary keys to map to values. Dictionaries are like associative arrays in
other programming languages.
6. Sets are mutable unordered collections of distinct immutable objects. So, while the set itself can be modified,
T
it cannothibe
s d populated with objects that can be modified.
oc
um
en
tb
elo
ja ng
N g s
Sequences
Sequences are iterables that can return members based on their position within the iterable. You have already
learned about one type of sequence: strings. Remember string indexing (see page 74):
Th world!'[1]
>>> 'Hello,
is
do
'e' cu
men
tb
elo
n
No jagta gs to
un at pone
That’s one way of getting NI
au nilkamember L of a sequence.
tho nt@ KAN
riz red TES
ed HW
The sequences we cover in this lessonc op ifare:
f.
ies com AR
all JA
ow GT
ed AP
1. Lists ! .
2. Tuples
3. Ranges
Th
is
do
cu
m
Lists tb
en
elo
n
No agta gs to
j
un pn NI
ilka in
Python’s lists are similarautotharrays Lother
K languages. Lists are created using square brackets, like this:
ori n t@ ANT
ze r
d c ediff ESH
op . WA
ies com R
all JA
colors = ["red", "blue", "green",ow"orange"] GT
ed AP
! .
List Methods
Some of theTmost common list methods are shown in the following list:
his
do
cu
me
mylist.append(x) nt – Appends x to mylist.
be
lo
N jag ngs
mylist.remove(x) ou to
tap– Removes first element with value of x from mylist. Errors if no such element is
na nil NI
u k L K
tho ant
found.
riz @ ANT
ed re ES
co diff.c HW
mylist.insert(i, x) – Inserts pie AR i.
xo at position
sa m JA
llo GT
we
mylist.count(x) – Returns the number d! of timesAthat
P. x appears in mylist.
mylist.index(x) – Returns the index position of the first element in mylist whose value is x or a
ValueError if no such element exists.
The followingThcode
is illustrates how these methods are used. Try this out at the Python shell:
do
cu
me
nt
be
lon
>>> colors = ["red",No ja gs
gta"blue", "green", "orange"]
un pn to NI
>>> colors a uth i lk a L K
ori nt@ ANT
z e re ES
co diff.c
['red', 'blue', 'green', d'orange'] HW
>>> colors.append("purple") #iesAppend
p AR
om purple
all JA to colors
ow GT
>>> colors ed AP
! .
['red', 'blue', 'green', 'orange', 'purple']
>>> colors.remove("green") # Remove green from colors
>>> colors
['red', 'blue', 'orange', 'purple']
>>> colors.insert(2,
T "yellow") # Insert yellow in position 2
his
>>> colors do
cu
en m
tb
['red', 'blue', 'yellow', 'orange', 'purple']
elo
jag ngs # Get position of orange
>>> colors.index("orange")
N tap outo
n naN
3 uth ilkan ILKA
ori t@ NT
ze colors
d c rediff ESH
>>> colors.sort() # Sort in place
>>> colors o pie .com WAR
sa JA
llo 'yellow']
GT
['blue', 'orange', 'purple', 'red', we AP
d! .
>>> colors.reverse() # Reverse order of colors
>>> colors
['yellow', 'red', 'purple', 'orange', 'blue']
>>> colors.pop() # Remove and return last element
'blue'
Th
is
do
>>> colors.pop(1) # Remove and return element at position 1
cu
'red'
m en
tb
e
lon and red have been removed
>>> colors # Noticej blueg
No agta s
pn to NI
un 'orange']
['yellow', 'purple',
au i l LK
tho kant
riz
>>> colors_copy = colors.copy() @ AN # Create a copy of colors
ed red TES
co if H
>>> colors_copy pie f.com WAR
sa JA
['yellow', 'purple', 'orange'] llo GT
we AP
d
>>> colors.extend(colors_copy) # Append colors_copy ! . to colors
>>> colors
['yellow', 'purple', 'orange', 'yellow', 'purple', 'orange']
>>> colors_copy.clear() # Delete all elements from colors_copy
>>> colors_copy # Notice colors_copy is now empty
Th
[] is
do
um c
>>> del colors_copy
e # Delete colors_copy
nt
be gone
>>> colors_copy # It'slo ng
ja
g call last): s
Traceback (mostN recent
File "<stdin>", line 1, in <module>
NameError: name 'colors_copy' is not defined
Copying a List
Note again how we made a copy of the colors list:
Th
is
do
cu
me
nt
b
>>> colors = ["red", e"blue", lon "green", "orange"]
No ja gta gs to
na pnilk NIL
>>> colors_copy =u colors.copy()
uth a K
>>> colors_copy ori nt@ ANT
ze re ES
['red', 'blue', 'green', d'orange'] co diff.c H
pie om WAR
>>> colors_copy.sort() s all JA
ow GT
ed AP
>>> colors_copy ! .
['blue', 'green', 'orange', 'red']
>>> colors
['red', 'blue', 'green', 'orange'] # colors remains unsorted
Th
is
You can see thatdsorting
oc
um colors_copy has no effect on the colors list. They are two distinct objects. Compare
en continues from the code above:
that to the following, whichtb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
>>> colors_copy2 = colors riz @ ANT
ed re ES
>>> colors_copy2 co diff.c HW
pie o AR
sa m JA
['red', 'blue', 'green', 'orange'] llo GT
we AP
d! .
>>> colors_copy2.sort()
>>> colors_copy2
['blue', 'green', 'orange', 'red']
>>> colors
['blue', 'green', 'orange', 'red'] # Wait! colors is sorted too!
hisT
>>> id(colors)d oc
2147162345152 um
en
b t
>>> id(colors_copy) elon
No jagta gs to
2147163702400 # different
u pn idN than colors
na ilk ILK
an u
>>> id(colors_copy2) tho A
riz t@re NTE
ed d SH
2147162345152 # the same id co as ifcolors
f.c W
pie om AR
sa JA
llo GT
we AP
! d .
Do you see what’s going on here? When you assign one variable to another, instead of making a copy, it just
creates a pointer to that object. If you modify one object, it affects both. The copy() method creates a brand new
identical object, so modifying the new object has no effect on the original.
Deleting
Th List Elements
is
do
c
The del statement ucan
me be used to delete elements or slices of elements from a list, like this:
nt
be
lon
N ja g gs
Demo 26: iterables/Demos/del_list.py
1. colors = ['red', 'blue', 'green', 'orange', 'black']
2.
3. del colors[0] # deletes first element
4. print(colors) # ['blue', 'green', 'orange', 'black']
5.
6. del colors[1:3] # deletes 2nd and 3rd elements
7. print(colors)
T # ['blue', 'black']
his
do
cu
men
tb
elo
n
No jagta gs to
Sequences and un Random
p
au nilka
NI
L
tho nt@ KAN
riz re TE
ed SH
co diff.c
In the Math lesson, when we learned pieabout omtheWrandom
AR module (see page 62), we mentioned two methods that we
s JA
were not yet ready to explore. Now, we aare: llo
we G TA
d! P.
random.choice(seq)
T
hs
>>> import irandom
do
cu
m
en "blue", "green", "orange"]
>>> colors = ["red",
tb
e
lon
>>> random.choice(colors)
j g
No agta st
oN
un p
au nilka
'orange' ILK
tho n A
>>> random.choice(colors) riz t@re NTE
ed d SH
co if
'green' pie f.com WAR
sa JA
llo GT
we AP
d! .
random.shuffle(seq)
Th
is
oc d
um
>>> import random
en
>>> colors = ["red",t b "blue", "green", "orange"]
elo
n
No agta gs to
j
>>> random.shuffle(colors)
pn un
NI
il LK
au
>>> colors tho kant
riz @ ANT
re
['green', 'red', 'blue', ed'orange'] ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .
Th
10isto 20 minutes
do
cu
me
nt
be
lon
N ja g gs
In this exercise, you will write a remove_random() function that removes a random element from a list and
returns it.
2. Write the code for the remove_random() function so that it removes and returns a random element from the
passed-in list: the_list.
Th
3. is main() function so that it uses remove_random() to remove a random element from the
Modify the do
cu
colors list andmthen
en prints something like the following:
tb
elo
n
No jagta gs to
un pn NI
au was il green.LK
tho kant
The removed color
@ AN
r ize are re['red', T
The remaining colors dc dif ESH 'blue', 'orange'].
op f . WA
ies com R
all JA
ow GT
ed AP
! .
1. import random
2. Th
is
oc d
3. def remove_random(the_list):
u me
nt
4. be
pass # replace this with your code
lon
5. No jagta gs to
u pn NI
def main(): nau il LK
6.
tho kant AN
r @
ize 'blue', TE
7. colors = ['red', d c rediff 'green',
S 'orange']
op .co HWA
8. # Your code here ies m R
all JA
9. ow GT
ed AP
! .
10. main()
Solution: iterables/Solutions/remove_random.py
Th
is
do
cu
1. import random me
nt
be
2. lon
No jagta gs to
3. def remove_random(the_list):
un p NI
au nilka LK
4. t h ori
x = random.choice(the_list) n t AN
ze @red TES
dc
5. the_list.remove(x) op iff.co HWA
ies m R
6. return x all JA
ow GT
ed AP
7. ! .
8. def main():
9. colors = ['red', 'blue', 'green', 'orange']
10. removed_color = remove_random(colors)
11. print(f'The removed color was {removed_color}.')
12. Th
print(f'The remaining colors are {colors}.')
is
do
cu
13. m en
tb
14. main() elo
jag ng
N s
Tuples
Tuples are like lists, but they are immutable: once created, they cannot be changed.
Get ready for a lie: Tuples are created using parentheses, like this:
Th
is
do
MAGENTA = (255,cum
0, 255)
en
tb
elo
n
No jagta gs to
pn
Wait, what??! Why areunyouau lyingil toNme?
ILK
tho kant
riz @ ANT
ed re ES
co diff.c HW
OK, the truth is that tuples are created pie withomcommasAR AND don’t require parentheses. You can create a tuple like
sa JA
this: llo GT
we AP
d! .
<class 'tuple'>
Th
<class 'tuple'>
is
d
oc recent call last):
Traceback (most um
en
tb
File "c:/Webucator/Python/iterables/Demos/tuples.py", line 12, in <module>
e lon
N jag gs
show_type( 255, 0, 255 )
TypeError: show_type() takes 1 positional argument but 3 were given
The takeaway Th here is: Always use parentheses when creating tuples.
is
do
cu
me
nt
b
Remember Constants elon
No agta gs to
j
un makes p N
The MAGENTA variable above au nialkagood Iconstant
LK (see page 18). The values represent the amounts of red, green, and blue in the color
magenta.
t h ori n t@ ANT
ze
d c rediff ESH
op . WA
ies com R
a JA
When to Use a Tuple llo
we GT
d! AP
.
While lists are used for holding collections of like data, tuples are meant for holding heterogeneous collections of
data. In tuples, the position of the element is meaningful. To illustrate, let’s consider our MAGENTA constant again:
T
line =his((-40,
d 10), (-80, 170))
c o
triangle = u((140,
me 200), (180, 270), (335, 180))
nt
be
rectangle = ((40, lo100),
n (80, 170), (235, 80), (195, 10))
N jag gs
Turtle Graphics
For a little fun, open and run the iterables/Demos/shapes.py file. It uses turtle
(https://docs.python.org/3/library/turtle.html), a built-in graphics library, to draw shapes from tuples of coordinates.
Th
Empty and Single-element Tuples
is
do
cu
You’re unlikely to have meto create empty or single-element tuples very often, but in case you do…
nt
be
lon
No ja gta gs to
Empty Tuple un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
t_empty = () sa JA
llo GT
we AP
d! .
To create a single-element tuple, follow the element with a comma, like this:
Th
is
do
cu
me
t_single = ("a",) nt
b elo
n
No jagta gs to
un pn N
uth ilkanyouILjust
If you do not include theacomma, KA get a string as illustrated in the following code:
ori t N
ze @red TES
dc iff HW
op .
ies com AR
all JA
>>> t1 = ("a",) o we GT
d! AP
.
>>> type(t1)
<class 'tuple'>
>>> t2 = ("a")
>>> type(t2)
<class 'str'>
T his
do
cu
m en
tb
elo
jag ngs
Ranges Nou ta to
na pnilk NIL
uth a KA
ori nt@of numbers
A range is an immutable sequence NT often used in for loops, which will be covered in the Flow Control
ze r
d c ediff ESH
lesson (see page 170). Ranges are .co using
opcreated WA range(), which can take one, two, or three arguments:
ies m R
all JA
ow GT
ed AP
! .
range(stop)
range(start, stop)
range(start, stop, step)
Th
is
do
The following examples show the options for creating a range:
cu
me
nt
be
lon
N ja g gs
range(10) # range starting at 0 and ending at 9
range(5, 11) # range starting at 5 and ending at 10
range(0, 13, 3) # range starting at 0, ending at 12, in steps of 3
range(4, -4, -1) # range starting at 4, ending at -3, in steps of -1
Note that the stop number is not included in the range. You should read it as "from start up to but not including
Th
stop." is
do
cu
me
nt
be
Converting Sequences lon to Lists
No ja gta gs to
u pn NI
The easiest way to seenhow au ranges il
tho kant work
LK in the Python shell is to convert them into lists first as shown in the
AN
following code: r ize @ T
d c rediff ESH
op . WA
ies com R
all JA
ow GT
ed AP
>>> list(range(10)) ! .
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(5, 11))
[5, 6, 7, 8, 9, 10]
>>> list(range(0, 13, 3))
Th
is 12]
[0, 3, 6, 9, do
cu
me 4))
>>> list(range(-4,n tb
elo 2, 3]
[-4, -3, -2, -1, 0, 1,
ja ng
No st
gta
u oN
pn
na
uth kan ILKA
i l
ori t@ NT
zediscuss
We will revisit ranges when we d c rediffor ESloops.
op f .co HWA
ies m R
all JA
ow GT
ed AP
Converting a Sequence to a List ! .
You can convert any type of sequence to a list with the list() function:
Again, indexing is the process of finding a specific element within a sequence of elements through the element’s
position. If we consider a sequence from left to right, the first element (the left-most) is at position 0. If we consider
a sequence from right to left, the first element (the right-most) is at position -1.
The followingThcode
is shows how to use indexing with a list, but the same can be done with any sequence type. Try
do
this out in the Pythoncu shell:
me
nt
be
lon
N ja g gs
>>> fruit = ['apple', 'orange', 'banana', 'pear', 'lemon', 'watermelon']
>>> fruit[0]
'apple'
>>> fruit[-1]
'watermelon'
>>> fruit[4]
'lemon' Th
is
>>> fruit[-3]doc
um
en
'pear' tb
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c WA
pie
Exercise 17: SimplesRock, all
o m Paper,
R
JA Scissors Game
ow GT
ed AP
! .
15 to 20 minutes
1. Open iterables/Exercises/roshambo.py
Th in your editor.
is
do
cu
2. Write the main() me function so that it:
nt
be
lo
A. CreatesNa sequence jag ngswith three elements: “Rock”, “Paper”, and “Scissors”.
ou tap to
na n N
uth ilkan ILKA
B. Makes a randomochoice riz t@for the
N computer and stores it in a variable.
ed red TES
co iff. H
C. Prompts the user with 1 pfor om WAR
ies cRock, 2 Jfor Paper, 3 for Scissors:
all AG
ow TA
ed P.
D. Prints out the computer’s choice and ! then the user’s choice.
Th
is
oc d
um Paper, 3 for Scissors: 1
1 for Rock, 2 for
en
Computer: Scissors t bel
on
User: Rock No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz r e TE
ed SH
co diff.c
pie om WAR
sa JA
Exercise Code: iterables/Exercises/roshambo.pyllo GT
we AP
d! .
1. import random
2.
3. def main():
4. pass # replace this with your code
Th
is
5. do
cu
men
6. main() tb
elo
jag ng
N s
Solution: iterables/Solutions/roshambo.py
1. import random
2.
3. def main():
4. roshambo = ["Rock", "Paper", "Scissors"]
5. Th
is
6. do
computer_choice = random.choice(roshambo)
c um
7. en
tb
elo
n
8.
No jagta gfor
num = input("1 s t Rock, 2 for Paper, 3 for Scissors: ")
o
u p
9. na
num = int(num) n il-k 1 NIL
u a K
th nt AN
10. user_choice =oriroshambo[num]
ze @re TE
dif SH
dc
f. WA
op
11. ies com R
all JA
12. ow
print("Computer:", computer_choice) GT
ed AP
13. print("User:", user_choice)
! .
14.
15. main()
Th
is
do
Slicing cu
m en
tb
elo a slice or segment of a sequence as a new sequence. The syntax is as follows:
Slicing is the process ofj gettingn
No agta gs to
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c
sub_sequence = orig_sequence[first_pos:last_pos] HW
pie o AR
sa m JA
llo GT
we AP
d! .
This returns a slice that starts with the element at first_pos and includes all the elements up to but not including
the element at last_pos.
Th
is
do
cu
me "d", "e"][:3]
>>> ["a", "b", "c",
n tb
['a', 'b', 'c']
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
r e
ed assumed ES
If last_pos is left out, then it is co diff.c to be HWthe length of the sequence, or in other words, one more than the
pie o AR
last position of the sequence. For example: sa m JA
llo GT
we AP
d! .
T
The following hcode
is
do shows how to slice a list, but the same can be done with any sequence type. Try this out in the
Python shell: cu
me
nt
be
lon
N ja g gs
>>> fruit = ["apple", "orange", "banana", "pear", "lemon", "watermelon"]
>>> fruit[0:5]
['apple', 'orange', 'banana', 'pear', 'lemon']
>>> fruit[1:4]
['orange', 'banana', 'pear']
>>> fruit[4:]
['lemon', T'watermelon']
his
do
>>> fruit[-3:] cu
m
['pear', 'lemon', e'watermelon']
nt
b elo
>>> fruit[:3] N ja ng
o u gtap s to N
['apple', 'orange', nil
na 'banana']ILK
u an k tho
t@ ANT riz
>>> fruit[-4:-1] ed re ES
co diff.c HW
p
['banana', 'pear', 'lemon'] ie o AR
sa m JA
llo GT
>>> fruit[:] we AP
d! .
['apple', 'orange', 'banana', 'pear', 'lemon', 'watermelon']
Exercise
Th
i
18: Slicing Sequences
sd
oc
um
en
tb
elo
10 to 20 jag ngs
Nominutes t t
un apni o NI
au lka LK
tho n A
riz t@re NTE
ed d SH
co if
1. Open iterables/Exercises/slicing.py pie f.com WAR in your editor.
sa JA
llo GT
we AP list that contains two lists: the first and second half of
2. Write the split_list() function so that d ! it returns a.
the original list. For example, when passed [1, 2, 3, 4], split_list() will return [ [1, 2], [3,
4] ].
3. If the original list has an odd number of elements, the function should put the extra element in the first list. For
example, when passed [1, 2, 3, 4, 5], split_list() will return [ [1, 2, 3], [4, 5] ].
Th
is
do
cu
me
nt
be
When you run the program, loitnshould output:
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz red TES
["red", "blue", "green"] d c
e
op iff.co HWA
ies m R
['orange', 'purple'] all JA
ow GT
ed AP
! .
1. import
T math
his
2. do
cu
en m
3. def split_list(orig_list):
t be
lo
4.
N jag ngthis
pass # replace s with your code
5.
6. def main():
7. colors = ["red", "blue", "green", "orange", "purple"]
8. colors_split = split_list(colors)
9. print(colors_split[0])
10. print(colors_split[1])
11.
Th
12. main()is do
cu
men
tb
elo
n
No jagta gs to
un p NI
au nilka
Solution: iterables/Solutions/slicing.py L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
1. import math sa JA
llo GT
we AP
2. d! .
3. def split_list(orig_list):
4. list_len = len(orig_list)
5. mid_pos = math.ceil(list_len/2)
6. list1 = orig_list[:mid_pos]
7. Th
list2 = orig_list[mid_pos:]
is
d
oc [list1, list2]
8. returnum
en
-------Lines 9t bthrough
e 16 Omitted-------
lon
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz red TES
ed
min(), max(), and sum() c op iff.co HWA
ies m R
all JA
ow GT
min(iter) and max(iter) ed AP
! .
The min(iter) function returns the smallest value of the passed-in iterable.
The max(iter) function returns the largest value of the passed-in iterable.
Th
is
do
cu
m
>>> colors = ["red", "blue", "green", "orange", "purple"]
en
tb
>>> min(colors) elo
ja ng
'blue' N ou g tap s to
na n N
>>> max(colors) uth ilkan ILKA
ori t N
ze @red TES
'red' dc iff.c H
op om WAR
>>> ages = [27, 4, 15, 99,ies 33, all 25] JA
ow GT
>>> min(ages) ed AP
! .
4
>>> max(ages)
99
Th
is
do uppercase letters are “smaller” than lowercase letters:
Note that, for strings,
cu
me
nt
be
lon
N ja g gs
>>> min("NatDunn")
'D'
The min() and max() functions can also take multiple arguments to compare. This is covered in the Math (see page 57) and Strings (see page
103) lessons. Th
is
do
cu
men
sum(iter[, start]) tb
elo
N jag ngs
The sum() function otakes to
tap iterable
un an ni NI and adds up all of its elements and then adds the result to start (if it is
passed in). For example:autho lkant LKAN
riz @ TE
ed re SH
co diff.c
pie om WAR
sa JA
llo GT
>>> nums = range(1, 6) we AP
d! .
>>> sum(nums) # 1 + 2 + 3 + 4 + 5
15
>>> sum(nums, 10)
25
Th
is
do
cu
men
tb
Converting Sequences
elo
n
to Strings with str.join(seq)
No jagta gs to
p
un a string N
The join() method of au nilkajoinsILthe elements of a sequence of strings on the given string. For example:
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
>>> colors = ["red", "blue", "green", llo GT
we "orange"] AP
d! .
>>> ','.join(colors)
'red,blue,green,orange'
>>> ', '.join(colors) # space after comma
'red, blue, green, orange'
>>> ':'.join(colors)
hisT
'red:blue:green:orange'
d oc
um
>>> ' '.join(colors)
e nt
b
elo
'red blue green orange' n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz r TE
ed ifeany
Note, the join() method will error of Sthe
H elements in the sequence is not a string.
co diff.c
pie om WAR
sa JA
llo GT
Splitting Strings into Lists we AP
d! .
The split() method of a string splits the string into substrings. By default it splits on whitespace. For example:
>>> sentence = 'We are no longer the Knights Who Say "Ni!"'
hisT
>>> list_of_words = sentence.split()
do
cu
>>> list_of_wordsm en
t
['We', 'are', 'no', b'longer',
elo 'the', 'Knights', 'Who', 'Say', '"Ni!"']
ja ng
N g s
split() takes an optional sep parameter to specify the separator:
split() takes a second optional parameter, maxsplit, to indicate the maximum number of times to split the
string. For example:
Th
is
do
cu
me banana, pear, melon"
>>> fruit = "apple,
n tb
>>> fruit.split(", ",elo2)
n
No jagta gs to
['apple', 'banana', pn
u 'pear, melon']
N
na IL ilka
nt@ KAN
uth
ori
ze T
d c rediff ESH
op .co WA
ies same
Notice pear and melon are part of the m stringR element. That’s because the string stopped splitting after two
all JA
ow GT
splits. ed AP
! .
The splitlines() method of a string splits a string into a list on line boundaries (i.e., line feeds (\n) and carriage
returns (\r)). For example:
Th
is
do
cu
me
>>> fruit = """apple nt
be
lon
banana No jagta gs to
un p NI
pear au nilka L
tho nt@ KAN
melon""" riz r e TE
ed SH
co diff.c
>>> fruit.splitlines() pie om WAR
sa JA
llo GT
['apple', 'banana', 'pear', 'melon'] we AP
d! .
The splitlines() method is really useful when reading files. Consider the following text file:
Code Explanation
Th
is
do
The file is a listing cofumstates in the United States. Each line lists the name of the state and its abbreviation,
en
separated by a newline. t be
lon
No jagta gs to
un pn
The following code can abe uthusedilkato Nread
ILK this file into a list:
ori nt@ ANT
ze
d c rediff ESH
op . WA
Demo 29: iterables/Demos/states.py ies com R
all JA
ow GT
ed AP
! .
1. def main():
2. with open('../data/states.txt') as f:
3. states = f.read().splitlines()
4.
5. Th
print(f'The file contains {len(states)} states.')
is
do
6. cu
men
7. main() tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
Code Explanation riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m
This will read the states from the file intollao list. Run Jthe
AG file:
we TA
d! P.
Th
is
As you will soon dsee,
oc having the data in a list makes it much easier to work with.
um
en
tb
elo
n
Unpacking Sequences No agta gs to
j
un pn
au ilka NILK
t h ori nt@ Aassignment
We learned earlier about simultaneous NT (see page 16), which allows you to assign values to multiple
ze
variables at once, like this: d c rediff ESH
op . WA
ies com R
all JA
ow GT
ed AP
! .
>>> first_name, last_name, company = "Nat", "Dunn", "Webucator"
>>> first_name
'Nat'
>>> last_name
'Dunn' Th
is
do
>>> company cu
men
'Webucator' tb
elo
jag ng
N s
You can use the same concept to unpack a sequence into multiple variables, like this:
Th {
>>> dict = is
do
'key1':cum
'value 1',
en
t b 2',
'key2': 'valuee lo
jag n3'g
tap s to
'key3':No'value
nil un
NI
auLK
} tho kant
riz @ ANT
>>> dict['key2'] = 'new e d c re2'
value d #ES assign new value to existing key
op iff.co HWA
>>> dict['key4'] = 'value 4' # i m
es assign value
R
all JA to new key
ow G
>>> print(dict['key1']) # print value ed of key TAP
! .
value 1
Th
is
Demo 30: iterables/Demos/dict.py
do
cu
me
nt
be
1. grades = { lon
No jagta gs to
un 97, p NI
2. "English": au nilka L
tho nt@ KAN
"Math": 93, riz
3.
ed red TES
4. "Global Studies": c85, op iff.co HWA
ies m R
all JA
5. "Art": 74, ow GT
ed AP
6. "Music": 86 ! .
7. }
8.
9. grades["Global Studies"] = 87 # assign new value to existing key
10. grades["Gym"] = 100 # assign value to new key
Th
11. is
do
cu
12. me
print(grades["Math"]) # print value of key
n tb
elo
jag ng
N s
Common Dictionary Methods
The code samples for the methods that follow assume this dictionary:
grades = {
"English": 97,
Th 93,
"Math":is
do
"Art": 74, cum
en
"Music": 86 tb
elo
n
} No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
mydict.get(key[, default]) llo GT
we AP
d! .
Returns the value for key if it is in mydict. Otherwise, it returns default if passed in or None if it is not.
>>> grades.get('English')
97
Th
is
do
>>> grades.get('French') # returns None
cu
me
>>> grades.get('French', 0)
n tb
0
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
mydict.pop(key[, default]) sa m JA
llo GT
we
Removes and returns the value of key if it is in! mydict.AOtherwise,
d P. it returns default if passed in or a KeyError
if it is not.
>>> grades.pop('English')
97 Th
is
>>> grades # dNotice
oc
u 'English' has been removed
me
nt 74, 'Music': 86}
{'Math': 93, 'Art': be
lo
jag ngs
>>> grades.pop('English')
N
po ta to
un Nlast):
au ncall
Traceback (most recent il ILK
tho kant AN
File "<stdin>", line ri1,
@ TE
ze in r<module>
dife dcS
f. HW op
KeyError: 'English' ies com AR
all JA
ow
>>> grades.pop('English', 'Not found') GT
ed AP
! .
'Not found'
mydict.popitem()
Th
is
do
cu
m
Removes and returns ethe
nt last key/value pair entered as a tuple. 27
be
lon
N ja g gs
>>> grades.popitem()
('Music', 86)
>>> grades # Notice 'Music' has been removed
{'Math': 93, 'Art': 74}
T
his
mydict.copy() d oc
um
en
tb
elo
n
No jagta gs to
Returns a copy of mydict.
un p NI
au nilka L
tho nt@ KAN
riz re ofTE
This works just like the copy()edmethod lists
SH (see page 115):
co diff.c WA
pie o
sa m R
JA
llo GT
we AP
d! .
>>> grades_copy = grades.copy()
>>> grades['English'] = 94 # Add 'English' back to grades
>>> grades['Music'] = 100 # Add 'Music' back to grades
>>> grades # Notice they're back
{'Math': 93, 'Art': 74, 'English': 94, 'Music': 100}
Th
is
do # But grades_copy still has the old data
>>> grades_copy
cu
en 74}
{'Math': 93, 'Art':
m
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c
mydict.clear() HW
pie o AR
sa m JA
llo GT
we AP
d! .
Removes all elements form mydict.
>>> grades.clear()
>>> grades # Dictionary is now empty
Th
{} is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
update()
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA pairs to a dictionary or to overwrite the values of existing keys
The update() method is used to add new llo key/value GT
we
or both. It can take several types of arguments. d! ConsiderAthe
P. following dictionary:
grades = {
"English": 97,
Th 93,
"Math":is
do
"Art": 74, cum
en
"Music": 86 tb
elo
jag ng
} N s
All three of the following statements would modify the value of the "Math" key and add a new "Gym" key:
setdefault()
Th
is
do
The setdefault(key, default) method works like this:
cu
me
nt
be
lon
If key does not No agtin
exist
j gs dictionary, key is added with a value of default.
the
un a pn to NI
au il L
tho kant theKAvalue
If key exists in the dictionary, N for key is left unchanged.
riz @
ed red TES
co if H
pie f.com WAR
sa JA
llo GT
we AP
The following example illustrates how setdefault() d! works:
.
1. grades = {
2. Th
"English": 97,
is
do
cu 93,
3. "Math":m en
4.
t
"Art": 74, belo
j
No 86ag ngs
5. "Music":
pnta to
ilun NI
au LK
tho kant
@ ANT
6. }
riz re ES
ed
7. co diff.c H
p om WAR
8. grades.setdefault("Art",ies87) all # Art key
JA exists. No change.
ow GT
9. print("Art grade:", grades["Art"]) ed AP
! .
10.
11. grades.setdefault("Gym", 97) # Gym key is new. Added and set.
12. print("Gym grade:", grades["Gym"])
Th
is
Code Explanationdo
cu
men
tb
elo
The preceding code willj render ng the following:
N a g s
Art grade: 74
Gym grade: 97
Notice that the value of the Art key did not change. setdefault() really means
add_key_unless_key_already_exists().
T
When to Use hsetdefault()
is
do
cu
me
nt
Imagine you are creating baedictionary
lon of grades from data in a file or a database. You cannot be sure what data that
Noyoujagneed gs
source contains, but t grades
t for four specific subjects. You can populate your dictionary using the external
un apni o NI
a
data, and then use setdefault()
uth lk a L
toKmake sure you have data for all keys:
ori nt@ ANT
ze r
d c ediff ESH
op . WA
ies com R
all JA
grades = get_data() # Imaginary function o we GT returns dictionary
that
d! AP
.
grades.setdefault('English') = 0
grades.setdefault('Math') = 0
grades.setdefault('Art') = 0
grades.setdefault('Music') = 0
Th
is
do
cu
The grade for any one meof the keys in the setdefault() calls will only be 0 if the dictionary returned by
nt
get_data() doesn’t include be that key.
lon
No agta gs to
j
un p NI
au nilka L
Dictionary View Objects tho nt@ KAN
riz re TE
ed SH
co diff.c WA
The following three methods return pdictionary
ies om view Robjects:
all JA
ow GT
ed AP
! .
mydict.keys()
Th
mydict.values()
is
do
cu
men
tb
elo
n
No agta gs to
j
mydict.items()nau p n N
uth ilkan ILKA
ori t N
ze @red TES
dc iff. HW
op
ies com AR
all JA
ow GT
ed AP
! .
Try this out in Python interactive mode:
>>> grades = {
"English": 97,
Th
is
"Math":
d 93,
oc
me u
"Art": 75 n tb
} elo
jag ng
N s
>>> grades.keys()
dict_keys(['English', 'Math', 'Art'])
>>> grades.values()
dict_values([97, 93, 75])
>>> grades.items()
dict_items([('English', 97), ('Math', 93), ('Art', 75)])
Th
is
do
cu
As you can see, dict_keys and dict_values look like simple lists and dict_items looks like a list of tuples.
me
nt
be they differ in two important ways:
But while they look like lists, lon
No jagta gs to
un p NI
aunot nsupport
il LK
1. Dictionary views do tho kant indexing or slicing as they have no set order.
riz @ ANT
ed red ES
co if HW
2. Dictionary views cannot be modified. pie f.coThey provide dynamic views into a dictionary. When the dictionary
A
sa m R
JA
changes, the views will change. llow GT
ed AP
! .
Th Art grade changes in the output (from 74 to 87). There was no need to reassign grade.values()
Notice that the is
d
to gradepointsoas cu gradepoints provides a dynamic view into the grades dictionary.
me
nt
be
lon
ja
To get a list from a Ndictionary
g view,gs use the list() method:
>>> grades = {
"English": 97,
"Math": 93,
"Art": 75
}
>>> list(grades.keys())
['English',
T 'Math', 'Art']
his
do
>>> list(grades.values())
c um
en
[97, 93, 75] tb
elo
n
No jagta gs to
>>> list(grades.items())
p
[('English', 97),un('Math', NI
au nilk 93),LK ('Art', 75)]
an tho
t@ ANT riz
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
Deleting Dictionary Keys d! .
The del statement can be used to delete a specific key from a dictionary, like this:
Th
is
1. grades =do{c
um
en 97,
2. "English": tb
elo
3. "Math": jag ng
N 93, ou oN tap st
na n ILK
4. uth ilkan 85,
"Global Studies":
ori t@ ANT
5. "Art": 74, ze re ES dif
dc f. HW
op
6. "Music": 86 ies com AR
all JA
7. } ow GT
ed AP
! .
8.
9. del grades["Math"] # deletes Math key
10. print(grades)
Th
is
oc d
The len() Function
um
en
tb
e
The len() function canj be loused n to determine the number of characters in a string or the number of objects in a list,
No agta gs to
tuple, dictionary, or set:
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c H
pie om WAR
>> len("hello") s all JA
ow GT
5 e d! AP
.
>>> len( ["a", "b", "c"] )
3
>>> len( (255, 0, 255) )
3
Th
>>> len({"Math": 97, "Music": 86, "Global Studies": 85})
is
do
3 cu
men
tb
elo
jag ng
N s
Exercise 19: Creating a Dictionary from User Input
15 to 25 minutes
Th
1. is
Open iterables/Exercises/gradepoints.py in your editor.
do
cu
me
2. Write the main()nfunction
tb
elo so that it:
ja ng
N gt st
A. Creates ao gradesun apnidictionaryoN
IL and populates it with grades entered by the user in English, Math, Global
au lka
Studies, Art, and t hoMusic. nt@ KAN
riz re TE
ed SH
co diff.c WA
B. Determines the average pgrade ies oand m printsR it out. Note, to do this you will need to convert the user input to
JA
all GT
integers. o we
d! AP
.
Th
is
English grade:do 98
cu
Math grade: 89
men
tb
elo
Global Studies grade:
ja 79 ng
No st gta
Art grade: 91 u oN pn
na
uth kan ILKA
i l
ori t N
Music grade: 84 ze @red TES
dc iff HW
op .
ies com
Your average is 88.2 AR
all JA
ow GT
ed AP
! .
Challenge
After printing the average, ask the user to change the grade in one subject and then get the new average and print
it out. Hint: you will have to prompt the user twice, once for the subject and once for the grade.
Th
is
do
Solution: iterables/Solutions/gradepoints.py
cu
me
nt
be
lon
1. def main(): No jagta gs to
un p NI
au nilka L
2. grades = {} tho nt@ KAN
riz r e TE
ed = int(input("English
SH
co diff.c
3. grades["English"] grade: "))
p o WA
4. grades["Math"] = int(input("Math i es m R grade: "))
all JA
ow GT
5. grades["Global Studies"] =edint(input("Global AP Studies grade: "))
! .
6. grades["Art"] = int(input("Art grade: "))
7. grades["Music"] = int(input("Music grade: "))
8.
9. gradepoints = grades.values()
10. Th
is
11. do
averagec = sum(gradepoints)/len(gradepoints)
um
en
12. tb
elo
13. print("Your ng
jag average is", average)
N s
14.
15. main()
1.
T
his
def avg(gradepoints):
do
cu = sum(gradepoints)/len(gradepoints)
2. averagem en
be t
3. return averagelo n
4. No jagta gs to
un p NI
au nilka L
5. def main(): tho nt@ KAN
riz re TE
ed SH
6. grades = {} co diff.c
pie om WAR
7. sa
grades["English"] = int(input("English JA grade: "))
llo GT
we A
8. grades["Math"] = int(input("Math d! P. "))
grade:
9. grades["Global Studies"] = int(input("Global Studies grade: "))
10. grades["Art"] = int(input("Art grade: "))
11. grades["Music"] = int(input("Music grade: "))
12.
13. Th
gradepoints = grades.values()
is
do
14. cu
me
n
average = tavg(gradepoints)
15. be
lon
16. ja gta
No g s
n pn to NI
u
a i lk Lis", average)
ho ant@ KAN
17. print("Yourut average
riz re TE
18. ed SH
co diff.c WA
19. subject = input("Choose p i es o m
a subjectR to change your grade: ")
all JA
GT
20. new_grade = input("What ow is
ed your new A"P + subject + " grade? ")
! .
21. grades[subject] = int(new_grade)
22. average = avg(gradepoints)
23.
24. print("Your new average is", average)
25. Th
s i
26. main() doc
um
en
tb
elo
n
No agta gs to
j
Code Explanation un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
Note that, as our program now requires co diffcalculating
H the average more than one time, we have moved that
pie . c om WAR
functionality into a new avg() function.al s JA
low GT
ed AP
! .
Sets
Sets are mutable unordered collections of distinct immutable objects. So, while the set itself can be modified, it
cannot be populated with objects that can be modified. You can also think of sets as dictionaries in which the keys
have no values. In fact, they can be created with curly braces, just like dictionaries:
Th
is
do
cu
me
nt
>>> classes = {"English", be
lon "Math", "Global Studies",
j
N"Art",a gs
g "Music"}
>>> type(classes)
<class 'set'>
Sets are less commonly used than the other iterables we’ve looked at in this lesson, but one great use for sets is to
remove duplicates from a list as shown in the following example:
Th
is
d
>>> veggies = o["tomato",
cu "spinach", "pepper", "pea", "tomato", "pea"]
me
nt
be
>>> v_set = set(veggies) # converts to set and remove duplicates
lon
>>> v_set No jagta gs to
un pn NI
il
au 'spinach', LK 'pea'}
{'pepper', 'tomato',
tho kant AN
r @
ize # converts T
>>> veggies = list(v_set) d c rediff ESHback to list
op . WA
>>> veggies ies com R
all JA
['pepper', 'tomato', 'spinach', 'pea'] o we GT
d! AP
.
Th
is
do
veggies will now ccontain:
um
en
tb
elo
n
No agta gs to
j
un pn NI
il
au 'spinach', LK 'pea']
['pepper', 'tomato',
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
*args and **kwargs d! .
When defining a function, you can include two special parameters to accept an arbitrary number of arguments:
*args – A parameter that begins with a single asterisk will accept an arbitrary number of non-keyworded
Th and store them in a tuple. Often the variable is named *args, but you can call it whatever you
arguments
is
want (e.g., d*people
oc or *colors). Note that any parameters that come after *args in the function signature
um
are keyword-onlyenparameters.
tb
elo
ja ng
**kwargs – N g
A parameter sthat begins with two asterisks will accept an arbitrary number of keyworded
arguments and store them in a dictionary. Often the variable is named **kwargs, but, as with *args, you
can call it whatever you want (e.g., **people or **colors. When included, **kwargs must be the last
parameter in the function signature.
Th
1. is
Non-keyword-only parameters that are required (i.e., have no defaults).
do
cu
me
2. Non-keyword-onlyntparameters
be that have defaults.
lon
No ja gt g st
3. *args un apni o NI
au lka LK
tho n A
riz t@re NTE
4. Keyword-only parametersed(with co or
d SH defaults).
ifwithout
pie f.com WAR
sa JA
5. **kwargs llo GT
we AP
d! .
Using *args
Earlier, we saw a function that looked like this:
Th
is
do
cu
me
def add_nums(num1, ntnum2, be num3=0, num4=0, num5=0):
lon
j g
a + num3 + num4 + num5
o u gtap s to N
sum = num1 N+ num2
n a nil ILK num3, "+",
print(num1, "+",u num2,
tho kant"+", AN
r @
ize " r=e ", TE
num4, "+", num5, dc dif sum) SH
op f . WA
ies com R
all JA
ow GT
ed AP
!
This works fine if you know that there will be between two and . five numbers passed into add_nums(), but you can
use *args to allow the function to accept an arbitrary number of numbers:
Th
1. is
def add_nums(num, *nums):
d oc
u
2. total =msum(nums,
en num)
b t
3. print(f"The esum
lon of {nums} and {num} is {total}.")
Noja g
st gta
4. u oN pn
na
uth lkan ILKA
i
ori t N
ze @red TES
5. def main():
d co if H
6. add_nums(1, 2) pie f.com WAR
7. add_nums(1, 2, 3, 4, 5)allo
s JA
we GT
d! AP
8. add_nums(11, 12, 13, 14) .
9. add_nums(101, 201, 301)
10.
11. main()
Th
is
Code Explanationdo
cu
me
nt
be
lo
This will output: N jag ngs
The sum of (2,) and 1 is 3.
The sum of (2, 3, 4, 5) and 1 is 15.
The sum of (12, 13, 14) and 11 is 50.
The sum of (201, 301) and 101 is 603.
Th
1. is
The add_nums() function requires one argument: num. It can also take zero or more subsequent arguments,
do
cu
m
which will all be stored
en in a single tuple, nums.
tb
elo
n
2. We use the built-in gta gs function
No jasum() to (see page 131) to get the sum of nums and add it to num.
un p NI
au nilka LK
tho n AN
3. The output is not perfect. riz Wet@will
redimprove
TE it later on.
ed
co iff. SHW
pie com AR
sa JA
llo GT
we AP
d! .
Using **kwargs
The **kwargs parameter is most commonly used when you need to pass an unknown number of keyword
arguments from one function to another. While this can be very useful (e.g., in decorators), it’s beyond the scope of
this lesson.
Th
is
Conclusiondocum
en
tb
elo
In this lesson, you have learned about lists, tuples, ranges, dictionaries, and sets. You also learned about the
N jag ngs
*args and **kwargs tap
o u parameters. to Soon, you’ll learn to search these iterables for values and to loop through them
na nil NI
k L
u
performing operations on each a
tho element nt@ KAthey N contain one by one.
riz red TES
ed H
co if
pie f.com WAR
sa JA
llo GT
we AP
d! .
27. In versions prior to 3.7, an arbitrary item was removed.
Th
is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .
Th
is
do
cu
men
tb
elo
jag ng
N s