0% found this document useful (0 votes)
9 views

Python 05 List Tuple

Python_05_List_Tuple

Uploaded by

2200010487
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python 05 List Tuple

Python_05_List_Tuple

Uploaded by

2200010487
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

LIST, TUPLE

Agenda
• List
• Tuple
• Exercise

2
List
Lists
• list: Python's equivalent to Java's array (but cooler)
– Declaring:
name = [value, value, ..., value] or,
name = [value] * length

– Accessing/modifying elements: (same as Java)


name[index] = value
>>> scores = [9, 14, 18, 19, 16]
[9, 14, 18, 19, 16]
>>> counts = [0] * 4
[0, 0, 0, 0]
>>> scores[0] + scores[4]
25

4
Indexing
• Lists can be indexed using positive or negative
numbers:
>>> scores = [9, 14, 12, 19, 16, 7, 24, 15]
[9, 14, 12, 19, 16, 7, 24, 15]
>>> scores[3]
19
>>> scores[-3]
7

index 0 1 2 3 4 5 6 7
value 9 14 12 19 16 7 24 15
index -8 -7 -6 -5 -4 -3 -2 -1

5
Recall: Strings
index 0 1 2 3 4 5 6 7
value P . D i d d y
-index -8 -7 -6 -5 -4 -3 -2 -1

>>> name = "P. Diddy"


• Accessing character(s): >>> name[0]
'P'
variable [ index ] >>> name[7]
variable [ index1:index2 ] 'y'
>>> name[-1]
'y'
>>> name[3:6]
– index2 exclusive 'Did'
>>> name[3:]
– index1 or index2 can be 'Diddy'
omitted (goes to end of string) >>> name[:-2]
'P. Did'

6
Slicing
• slice: A sub-list created by specifying start/end
indexes
name[start:end] # end is exclusive
name[start:] # to end of list
name[:end] # from start of list
name[start:end:step] #
>>> scores = [9, 14, 12, 19, every
16, step'th
18, 24, 15] value
>>> scores[2:5]
[12, 19, 16]
>>> scores[3:]
[19, 16, 18, 24, 15]
>>> scores[:3]
[9, 14, 12]
>>> scores[-3:] index 0 1 2 3 4 5 6 7
[18, 24, 15]
value 9 14 12 19 16 18 24 15
index -8 -7 -6 -5 -4 -3 -2 -1 7
Other List Abilities
– Lists can be printed (or converted to string with str()).
– Find out a list's length by passing it to the len function.
– Loop over the elements of a list using a for ... in loop.
>>> scores = [9, 14, 18, 19]
>>> print("My scores are", scores)
My scores are [9, 14, 18, 19]
>>> len(scores)
4
>>> total = 0
>>> for score in scores:
... print("next score:", score)
... total += score
next score: 9
next score: 14
next score: 18
next score: 19
>>> total
60
8
Ranges, Strings, and Lists
• The range function returns a list.
>>> nums = range(5)
>>> nums
[0, 1, 2, 3, 4]
>>> nums[-2:]
[3, 4]
>>> len(nums)
5

• Strings behave like lists of characters:


– len
– indexing and slicing
– for ... in loops

9
String Splitting
• split breaks a string into a list of tokens.
name.split() # break by
whitespace
name.split(delimiter) # break by delimiter

• join performs the opposite of a split


delimiter.join(list)

>>> name = "Brave Sir Robin"


>>> name[-5:]
'Robin'
>>> tokens = name.split()
['Brave', 'Sir', 'Robin']
>>> name.split("r")
['B', 'ave Si', ' Robin']
>>> "||".join(tokens)
'Brave||Sir||Robin' 10
Tokenizing File Input
• Use split to tokenize line contents when reading files.
– You may want to type-cast tokens: type(value)

>>> f = open("example.txt")
>>> line = f.readline()
>>> line
'hello world 42 3.14\n'

>>> tokens = line.split()


>>> tokens
['hello', 'world', '42', '3.14']

>>> word = tokens[0]


'hello'
>>> answer = int(tokens[2])
42
>>> pi = float(tokens[3])
3.14
11
Exercise
• Recall hours.txt. Suppose the # of days can
vary:
123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5

• Compute each worker's total hours and hours/day.


– Should work no matter how many days a person works.
Suzy ID 123 worked 31.4 hours: 6.3 / day
Brad ID 456 worked 36.8 hours: 7.36 / day
Jenn ID 789 worked 39.5 hours: 7.9 / day

12
Exercise Answer
hours.py
1 file = open("hours.txt")
2 for line in file:
3 tokens = line.split()
4 id = tokens[0]
5 name = tokens[1]
6
7 # cumulative sum of this employee's hours
8 hours = 0.0
9 days = 0
10 for token in tokens[2:]:
11 hours += float(token)
12 days += 1
13
14 print(name, "ID", id, "worked", \
15 hours, "hours:", hours / days, "/ day")

13
Exercise
• Suppose we have a file of midterm scores,
scores.txt:
76
89
76
72
68

• Create a histogram of the scores as follows:


75: *
76: *****
79: **
81: ********
82: ******
84: ***********

14
Exercise
• Suppose we have Internet Movie Database (IMDb)
data:
1 9.1 196376 The Shawshank Redemption (1994)
2 9.0 139085 The Godfather: Part II (1974)
3 8.8 81507 Casablanca (1942)

• Write a program to search for all films with a given


phrase:
Search word? part
Rank Votes Rating Title
2 139085 9.0 The Godfather: Part II (1974)
40 129172 8.5 The Departed (2006)
95 20401 8.2 The Apartment (1960)
192 30587 8.0 Spartacus (1960)
4 matches.

15
Exercise Answer
movies.py
1 search_word = input("Search word? ")
2 matches = 0
3 file = open("imdb.txt")
4 for line in file:
5 tokens = line.split()
6 rank = int(tokens[0])
7 rating = float(tokens[1])
8 votes = int(tokens[2])
9 title = " ".join(tokens[3:])
10
11 # does title contain search_word?
12 if search_word.lower() in title.lower():
13 matches += 1
14 print(rank, "\t", votes, "\t", rating, "\t", title)
15
16 print(matches, "matches.")

16
Tuple
Tuple
tuple_name = (value, value, ..., value)
– A way of "packing" multiple values into one variable
>>> x = 3
>>> y = -5
>>> p = (x, y, 42)
>>> p
(3, -5, 42)

name, name, ..., name = tuple_name


– "unpacking" a tuple's contents into multiple variables
>>> a, b, c = p
>>> a
3
>>> b
-5
>>> c
42
18
Using Tuples
• Useful for storing multi-dimensional data (e.g. (x,
y) points) >>> p = (42, 79)

• Useful for returning more than one value


>>> from random import *
>>> def roll2():
... die1 = randint(1, 6)
... die2 = randint(1, 6)
... return (die1, die2)
...
>>> d1, d2 = roll2()
>>> d1
6
>>> d2
4

19
Tuple as Parameter
def name( (name, name, ..., name), ... ):
statements

– Declares tuple as a parameter by naming each of its pieces

>>> def slope((x1, y1), (x2, y2)):


... return (y2 - y1) / (x2 - x1)
...
>>> p1 = (2, 5)
>>> p2 = (4, 11)
>>> slope(p1, p2)
3

20
Tuple as Return
def name(parameters):
statements
return (name, name, ..., name)

>>> from random import *


>>> def roll2():
... die1 = randint(1, 6)
... die2 = randint(1, 6)
... return (die1, die2)
...
>>> d1, d2 = roll2()
>>> d1
6
>>> d2
4

21
Exercise
• Write a program that performs a graphical "random walk".
– Create a DrawingPanel of size 150x150.
– Draw a circle of radius 75.
– Start a "walker" pixel at (75, 75), the circle's center.
– Every 10 ms, randomly move the walker by 1 pixel in
either the x or y direction and redraw the walker.
– Once the walker reaches the edge of the circle, stop walking.

• Key questions:
– How do we randomly move by 1 pixel?
– How do we know when we have reached
the edge of the circle?

22

You might also like