0% found this document useful (0 votes)
22 views123 pages

Gaddis Python 4e Chapter 07 PPT - combinedForLesson4

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

Gaddis Python 4e Chapter 07 PPT - combinedForLesson4

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

CHAPTER 7

Lists and
Tuples

Copyright © 2018 Pearson Education, Ltd.


Topics
• Sequences
• Introduction to Lists
• List Slicing
• Finding Items in Lists with the in
Operator
• List Methods and Useful Built-in
Functions

Copyright © 2018 Pearson Education, Ltd.


Topics (cont’d.)
• Copying Lists
• Processing Lists
• Two-Dimensional Lists
• Tuples
• Plotting List Data with the matplotlib
Package

Copyright © 2018 Pearson Education, Ltd.


Programming
• Algorithm
- A set of rules or steps used to solve a
problem

• Data Structure
- A particular way of organizing data in a
computer
https://en.wikipedia.org/wiki/Algorithm
https://en.wikipedia.org/wiki/Data_structure
What is Not a “Collection”?

Most of our variables have one value in them -


when we put a new value in the variable, the old
value is overwritten

$ python
>>> x = 2
>>> x = 4
>>> print(x)
4
Sequences
• Sequence: an object that contains
multiple items of data
• The items are stored in sequence one after
another
• Python provides different types of
sequences, including lists and tuples
• The difference between these is that a list is
mutable and a tuple is immutable

Copyright © 2018 Pearson Education, Ltd.


Introduction to Lists
• List: an object that contains multiple data
items
• Element: An item in a list
• Format: list = [item1, item2, etc.]
• Can hold items of different types
• print function can be used to display an
entire list
• list() function can convert certain types of
objects to lists

Copyright © 2018 Pearson Education, Ltd.


Introduction to Lists (cont’d.)

Copyright © 2018 Pearson Education, Ltd.


A List is a Kind of
Collection
• A collection allows us to put many values in a single
“variable”
• A collection is nice because we can carry all many
values around in one convenient package.

friends = [ ‘Ali', ‘Gizem', ‘Sinem' ]

carryon = [ 'socks', 'shirt', 'perfume' ]


List Constants
• List constants are
surrounded by >>> print([1, 24, 76])
square brackets and [1, 24, 76]
the elements in the >>> print(['red', 'yellow', 'blue'])
list are separated by ['red', 'yellow', 'blue']
commas >>> print(['red', 24, 98.6])
['red', 24, 98.6]
• A list element can be >>> print([ 1, [5, 6], 7])
any Python object - [1, [5, 6], 7]
even another list >>> print([])
[]
• A list can be empty
The Repetition Operator and
Iterating over a List
• Repetition operator: makes multiple copies
of a list and joins them together
• The * symbol is a repetition operator when applied to
a sequence and an integer
• Sequence is left operand, number is right
• General format: list * n
• You can iterate over a list using a for loop
• Format: for x in list:

Copyright © 2018 Pearson Education, Ltd.


The Repetition Operator and
Iterating over a List
numbers = [1, 2, 3] * 3
print (numbers)
Output_1 : [1, 2, 3, 1, 2, 3, 1, 2, 3]

numbers = [99, 100, 101, 102]


for n in numbers:
print(n)
Output_2:
99
100
101
102

Copyright © 2018 Pearson Education, Ltd.


We Already Use Lists!

5
for i in [5, 4, 3, 2, 1] : 4
print(i) 3
print('Blastoff!') 2
1
Blastoff!
Lists and Definite Loops - Best Pals

friends = [‘Ali', ‘Gizem', ‘Sinem'] Happy New Year: Ali


for friend in friends : Happy New Year: Gizem
print('Happy New Year:', friend) Happy New Year: Sinem
print('Done!') Done!

z = [‘Ali', ‘Gizem', ‘Sinem']


for x in z:
print('Happy New Year:', x)
print('Done!')
Indexing
• Index: a number specifying the position
of an element in a list
• Enables access to individual element in list
• Index of first element in the list is 0, second
element is 1, and n’th element is n-1
• Negative indexes identify positions relative to
the end of the list
• The index -1 identifies the last element, -2
identifies the next to last element, etc.

Copyright © 2018 Pearson Education, Ltd.


Indexing
my_list = [10, 20, 30, 40]
print (my_list[0], my_list[1], my_list[2], my_list[3])

Output_1: 10 20 30 40

my_list = [10, 20, 30, 40]


print (my_list[-1], my_list[-2], my_list[-3], my_list[-4])

Output_2: 40 30 20 10

Copyright © 2018 Pearson Education, Ltd.


What is printed by the
following statements?
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14,
False]
print(alist[5])

A. [ ]
B. 3.14
C. False
D. "dog"

Copyright © 2018 Pearson Education, Ltd.


Example
• Assign the value of the 8th element of
lst to the variable output.

lst = ["hi", "morning", "dog", "506",


"caterpillar", "balloons", 106, "yo-yo",
"python", "moon", "75.6"]

Copyright © 2018 Pearson Education, Ltd.


Example

n_lst = lst[8]

print(lst)
print(n_lst)

Copyright © 2018 Pearson Education, Ltd.


Looking Inside Lists

Just like strings, we can get at any single element in a list


using an index specified in square brackets

>>> friends = [ ‘Ali’, ‘Gizem', ‘Sinem' ]


Joseph Glenn Sally >>> print(friends[1])
0 1 2 Gizem
>>>
The len function
• An IndexError exception is raised if an
invalid index is used
• len function: returns the length of a
sequence such as a list
• Example: size = len(my_list)
• Returns the number of elements in the list, so the
index of last element is len(list)-1
• Can be used to prevent an IndexError exception
when iterating over a list with a loop

Copyright © 2018 Pearson Education, Ltd.


Example

alist = ["hello", 2.0, 5]

print(len(alist))

print(len(alist[0]))

Copyright © 2018 Pearson Education, Ltd.


What is printed by the
following statements?
L = [0.34, '6', 'SI106', 'Python', -2]
print(len(L[1:-1]))

A. 2
B. 3
C. 4
D. 5

Copyright © 2018 Pearson Education, Ltd.


The len function
my_list = [10, 20, 30, 40]
size = len(my_list)

index = 0
while index < len(my_list):
print (my_list [index])
index += 1

Output:
10
20
30
40

Copyright © 2018 Pearson Education, Ltd.


How Long is a List?
• The len() function
takes a list as a
parameter and >>> greet = 'Hello Bob'
returns the number >>> print(len(greet))
of elements in the 9
list >>> x = [ 1, 2, 'joe', 99]
>>> print(len(x))
• Actually len() tells us 4
the number of >>>
elements of any set
or sequence (such
as a string...)
Using the range Function
• The range
function returns a
list of numbers
>>> print(range(4))
that range from [0, 1, 2, 3]
zero to one less >>> friends = [‘Ali', ‘Gizem', ‘Sinem']
than the >>> print(len(friends))
parameter 3
>>> print(range(len(friends)))
[0, 1, 2]
• We can construct >>>
an index loop
using for and an
integer iterator
A Tale of Two Loops...
friends = [‘Ali', ‘Gizem', ‘Sinem']
Happy New Year: Ali
for friend in friends :
Happy New Year: Gizem
print('Happy New Year:', friend)
Happy New Year: Sinem
for i in range(len(friends)) :
friend = friends[i]
print('Happy New Year:', friend)

>>> friends = [‘Ali', ‘Gizem', ‘Sinem']


>>> print(len(friends))
3
>>> print(range(len(friends)))
[0, 1, 2]
>>>
Lists Are Mutable
• Mutable sequence: the items in the sequence
can be changed
• Lists are mutable, and so their elements can be
changed
• An expression such as
• list[1] = new_value can be used to
assign a new value to a list element
• Must use a valid index to prevent raising of an
IndexError exception

Copyright © 2018 Pearson Education, Ltd.


Lists Are Mutable

numbers = [1, 2, 3, 4, 5]
print (numbers)
numbers[0] = 80
print (numbers)

Output_1: [1, 2, 3, 4, 5]

Output_2: [80, 2, 3, 4, 5]

Copyright © 2018 Pearson Education, Ltd.


Lists are Mutable
• Strings are
>>> fruit = ‘BaNaNa'
“immutable” - we >>> fruit[0] = 'b'
cannot change the Traceback
contents of a string - TypeError: 'str' object does not
we must make a new support item assignment
>>> x = fruit.lower()
string to make any
>>> print(x)
change banana
>>> lotto = [2, 14, 26, 41, 63]
• Lists are “mutable” - >>> print(lotto)
we can change an [2, 14, 26, 41, 63]
element of a list >>> lotto[2] = 28
>>> print(lotto)
using the index
[2, 14, 28, 41, 63]
operator
Concatenating Lists
• Concatenate: join two things together
• The + operator can be used to
concatenate two lists
– Cannot concatenate a list with another data
type, such as a number
• The += augmented assignment
operator can also be used to
concatenate lists

Copyright © 2018 Pearson Education, Ltd.


Concatenating Lists
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]

list3 = list1 + list2

Output_1 : [1, 2, 3, 4, 5, 6, 7, 8 ]

list1 += list2
list1

Output_2: [1, 2, 3, 4, 5, 6, 7, 8 ]

Copyright © 2018 Pearson Education, Ltd.


Example
fruit = ["apple","orange","banana","cherry"]

print([1,2] + [3,4])

print(fruit + [6,7,8,9])

print([0] * 4)

Copyright © 2018 Pearson Education, Ltd.


What is printed by the
following statements?
alist = [1,3,5]
print(alist * 3)

•A. 9
•B. [1,1,1,3,3,3,5,5,5]
•C. [1,3,5,1,3,5,1,3,5]
•D. [3,9,15]

Copyright © 2018 Pearson Education, Ltd.


Concatenating Lists Using +
We can create a new list by adding two existing lists together.

>>> a = [1, 2, 3]
>>> b = ['x', 'y', 'z']
>>> c = a + b
>>> print(c)
[1, 2, 3, 'x', 'y', 'z']
>>> print(a)
[1, 2, 3]
List Slicing
• Slice: a span of items that are taken from a
sequence
• List slicing format: list[start : end]
• Span is a list containing copies of elements from
start up to, but not including, end
• If start not specified, 0 is used for start index
• If end not specified, len(list) is used for end index
• Slicing expressions can include a step value and
negative indexes relative to end of list

Copyright © 2018 Pearson Education, Ltd.


List Slicing
numbers = [1, 2, 3, 4, 5]
print (numbers[1:3])
[2, 3]

print (numbers[:3])
[1, 2, 3]

print (numbers[2:])
[3, 4, 5]

print (numbers[:])
[1, 2, 3, 4, 5]

Copyright © 2018 Pearson Education, Ltd.


Example
• Create a new list using the 9th through 12th
elements (four items in all) of new_lst and
assign it to the variable sub_lst.

new_lst = ["computer", "luxurious", "basket",


"crime", 0, 2.49, "institution", "slice", "sun",
["water", "air", "fire", "earth"], "games", 2.7,
"code", "java", ["birthday", "celebration",
1817, "party", "cake", 5], "rain",
"thunderstorm", "top down"]

Copyright © 2018 Pearson Education, Ltd.


Example
>>> sub_lst = new_lst[9:13]
>>> print(sub_lst)
[['water', 'air', 'fire', 'earth'], 'games', 2.7, 'code']
>>> a_lst = sub_lst[0]
>>> print(a_lst[1])
air
>>> print(sub_lst[0][1])
air
>>>

Copyright © 2018 Pearson Education, Ltd.


Lists Can Be Sliced Using :

>>> t = [9, 41, 12, 3, 74, 15]


>>> t[1:3]
[41,12]
>>> t[:4] Remember: Just like
[9, 41, 12, 3] in strings, the second
>>> t[3:] number is “up to but
[3, 74, 15] not including”
>>> t[:]
[9, 41, 12, 3, 74, 15]
Example
>>> new_lst[0:10:2]
['computer', 'basket', 0, 'institution', 'sun']
>>> new_lst[15:5:-3]
['rain', 'code', ['water', 'air', 'fire', 'earth'], 'institution']
>>> new_lst[::-2]
['top down', 'rain', 'java', 2.7, ['water', 'air', 'fire', 'earth'], 'slice',
2.49, 'crime', 'luxurious']
>>> new_lst[3::4]
['crime', 'slice', 2.7, 'rain']
>>> new_lst[:9:-2]
['top down', 'rain', 'java', 2.7]
>>> new_lst[:9:3]
['computer', 'crime', 'institution']
>>>

Copyright © 2018 Pearson Education, Ltd.


Finding Items in Lists with the
in Operator
• You can use the in operator to determine
whether an item is contained in a list
• General format: item in list
• Returns True if the item is in the list, or False if it is
not in the list
• Similarly you can use the not in operator to
determine whether an item is not in a list

Copyright © 2018 Pearson Education, Ltd.


Finding Items in Lists with the
in Operator
# This program demonstrates the in operator
# used with a list.
# Create a list of product numbers.
prod_nums = ['V475', 'F987', 'Q143', 'R688’]
# Get a product number to search for.
search = input('Enter a product number: ‘)
# Determine whether the product number is in the list.
if search in prod_nums:
print(search, 'was found in the list.’)
else:
print(search, 'was not found in the list.')

Copyright © 2018 Pearson Education, Ltd.


Is Something in a List?

• Python provides two


operators that let
>>> some = [1, 9, 21, 10, 16]
you check if an item >>> 9 in some
is in a list True
>>> 15 in some
• These are logical False
operators that return >>> 20 not in some
True or False True
>>>
• They do not modify
the list
List Methods and Useful Built-
in Functions
• append(item): used to add items to a list – item is
appended to the end of the existing list
• index(item): used to determine where an item is
located in a list
• Returns the index of the first element in the list
containing item
• Raises ValueError exception if item not in the list
• count(item):The method then returns the number
of times that the argument occured in the string/list
the method was used on.

Copyright © 2018 Pearson Education, Ltd.


Index Example
bio = ["Metatarsal", "Metatarsal", "Fibula", [],
"Tibia", "Tibia", 43, "Femur", "Occipital",
"Metatarsal"]

print(bio.index("Metatarsal"))
print(bio.index([]))
print(bio.index(43))

seasons = ["winter", "spring", "summer", "fall"]


print(seasons.index("autumn")) #Error!

Copyright © 2018 Pearson Education, Ltd.


Index Example
• What will be stored in the variable ht
below?

rooms = ['bathroom', 'kitchen', 'living room',


'bedroom', 'closet', "foyer"]
ht = rooms.index("garden")

• A. 0
• B. -1
• C. There is an error.
Copyright © 2018 Pearson Education, Ltd.
Count Example
z = ['atoms', 4, 'neutron', 6, 'proton', 4,
'electron', 4, 'electron', 'atoms']

print(z.count("4"))
print(z.count(4))
print(z.count("a"))
print(z.count("electron"))

Copyright © 2018 Pearson Education, Ltd.


Count Example
>>> z.index("electron")
6
>>> a = z[6]
>>> a
'electron'
>>> a.count('e')
2
>>> z.index('atoms')
0
>>> b = z[0]
>>> b.count('a')
1
Copyright © 2018 Pearson Education, Ltd.
List Methods and Useful Built-
in Functions
# First, create an empty list.
name_list = []
again = 'Y’
while again == 'Y’:
name = input('Enter a name: ')
name_list.append(name)
print('Do you want to add another name?')
again = input(‘Y = Yes, N = No or anything else: ')
print()
print('Here are the names you entered.’)
for name in name_list:
print(name)
Copyright © 2018 Pearson Education, Ltd.
List Methods and Useful Built-
in Functions
Enter a name: AHMET
Do you want to add another name?
Y = Yes, N = No or anything else: Y

Enter a name: ALİ


Do you want to add another name?
Y = Yes, N = No or anything else: Y

Enter a name: VELİ


Do you want to add another name?
Y = Yes, N = No or anything else: N

Here are the names you entered.


AHMET
ALİ
VELİ
Copyright © 2018 Pearson Education, Ltd.
List Methods

>>> x = list()
>>> type(x)
<type 'list'>
>>> dir(x)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
>>>

http://docs.python.org/tutorial/datastructures.html
Building a List from Scratch
• We can create an
empty list and then
add elements >>> stuff = list()
>>> stuff.append('book')
using the append
>>> stuff.append(99)
method
>>> print(stuff)
['book', 99]
• The list stays in
>>> stuff.append('cookie')
order and new >>> print(stuff)
elements are ['book', 99, 'cookie']
added at the end
of the list
List Methods and Useful Built-
in Functions (cont’d.)
• insert(index, item): used to insert
item at position index in the list
• sort(): used to sort the elements of
the list in ascending order
• remove(item): removes the first
occurrence of item in the list
• reverse(): reverses the order of the
elements in the list

Copyright © 2018 Pearson Education, Ltd.


Copyright © 2018 Pearson Education, Ltd.
Index
food = ['Pizza', 'Burgers', 'Chips']
print('Here are the items in the food list:')
print(food)
item = input('Which item should I change? ')
item_index = food.index(item)
new_item = input('Enter the new value: ')
food[item_index] = new_item
print('Here is the revised list:')
print(food)

Copyright © 2018 Pearson Education, Ltd.


Index
Output:

Here are the items in the food list:


['Pizza', 'Burgers', 'Chips’]
Which item should I change? Chips
Enter the new value: Cola
Here is the revised list:
['Pizza', 'Burgers', 'Cola']

Copyright © 2018 Pearson Education, Ltd.


Insert
# Create a list with some names.
names = ['James', 'Kathryn', 'Bill']
# Display the list.
print('The list before the insert:')
print(names)
# Insert a new name at element 0.
names.insert(0, 'Joe')
# Display the list again.
print('The list after the insert:')
print(names)

Output:
The list before the insert:
['James', 'Kathryn', 'Bill']
The list after the insert:
['Joe', 'James', 'Kathryn', 'Bill']

Copyright © 2018 Pearson Education, Ltd.


Sort
my_list = [ 9, 5, 0, 1, 89, 100, 3]
print (my_list)
my_list.sort()
print('Sorted list:', my_list)

Output:
[ 9, 5, 0, 1, 89, 100, 3]
Sorted list: [ 0, 1, 3, 5, 9, 89, 100]

Copyright © 2018 Pearson Education, Ltd.


Lists are in Order
• A list can hold many
items and keeps
those items in the
order until we do >>> friends = ['Sinem', 'Ali', 'Gizem' ]
something to change >>> friends.sort()
the order
>>> print(friends)
• A list can be sorted ['Ali', 'Gizem', 'Sinem']
(i.e., change its >>> print(friends[1])
order) Gizem
• The sort method >>>
(unlike in strings)
means “sort
yourself”
Remove
food = ['Pizza', 'Burgers', 'Chips’]
print('Here are the items in the food list:’)
print(food)
# Get the item to change.
item = input('Which item should I remove? ')
# Remove the item.
food.remove(item)
print('Here is the revised list:’)
print(food)

Copyright © 2018 Pearson Education, Ltd.


Remove

Output:

Here are the items in the food list:


['Pizza', 'Burgers', 'Chips']
Which item should I remove? Pizza
Here is the revised list:
['Burgers', 'Chips']

Copyright © 2018 Pearson Education, Ltd.


List Methods and Useful Built-
in Functions (cont’d.)
• del statement: removes an element from a
specific index in a list
• General format: del list[i]
• min and max functions: built-in functions
that returns the item that has the lowest or
highest value in a sequence
• The sequence is passed as an argument

Copyright © 2018 Pearson Education, Ltd.


Reverse & Deletion & Min & Max
my_list = [ 1, 2, 3, 4, 5]
print ("Original Order:", my_list)
my_list.reverse()
print("Reversed:", my_list)
del my_list[2]
print("After deletion:", my_list)
print("The lowest is" , min(my_list))
print("The highest is" , max(my_list))

Original Order: [ 1, 2, 3, 4, 5]
Reversed: [ 5, 4, 3, 2, 1]
After deletion:[ 5, 4, 2, 1]
The lowest is 1
The highest is 5
Copyright © 2018 Pearson Education, Ltd.
Built-in Functions and Lists

• There are a >>> nums = [3, 41, 12, 9, 74, 15]


number of >>> print(len(nums))
functions built 6
into Python that >>> print(max(nums))
74
take lists as
>>> print(min(nums))
parameters
3
>>> print(sum(nums))
• Remember the
154
loops we built? >>> print(sum(nums)/len(nums))
These are 25.6
much simpler.
Join Function
• You choose a desired separator string, (often
called the glue) and join the list with the glue
between each of the elements.

wds = ["red", "blue", "green"]


glue = ';'
s = glue.join(wds)
print(s)
print(wds)

print("***".join(wds))
print("".join(wds))

Copyright © 2018 Pearson Education, Ltd.


Join Function
>>> wds = ["red", "blue", "green"]
>>> glue = ';'
>>> s = glue.join(wds)
>>> print(s)
red;blue;green
>>> print(wds)
['red', 'blue', 'green']
>>> print("***".join(wds))
red***blue***green
>>> print("".join(wds))
redbluegreen
>>> print(" ".join(wds))
red blue green
>>>
Copyright © 2018 Pearson Education, Ltd.
Copying Lists
• To make a copy of a list you must copy each element
of the list
• Two methods to do this:
• Creating a new empty list and using a for loop to
add a copy of each element from the original list to
the new list
• Creating a new empty list and concatenating the
old list to the new empty list
list1 = [1, 2, 3, 4]
list2 = []
for item in list1:
list2.append(item)

Copyright © 2018 Pearson Education, Ltd.


Copying Lists
• Creating a new empty list and concatenating the old list
to the new empty list
list1 = [1, 2, 3, 4]
list2 = [] + list1

However if;
list1 = [1, 2, 3, 4]
list2 = list1

both variables list1 and list2 will reference the same list in
memory.

Copyright © 2018 Pearson Education, Ltd.


Copying Lists (cont’d.)

Copyright © 2018 Pearson Education, Ltd.


Processing Lists
• List elements can be used in calculations
• To calculate total of numeric values in a list
use loop with accumulator variable
• To average numeric values in a list:
• Calculate total of the values
• Divide total of the values by len(list)
• List can be passed as an argument to a
function

Copyright © 2018 Pearson Education, Ltd.


Totaling the Values in a List
# Create a list.
numbers = [2, 4, 6, 8, 10]
# Create a variable to use as an accumulator.
total = 0
# Calculate the total of the list elements.
for value in numbers:
total += value
# Display the total of the list elements.
print('The total of the elements is', total)

The total of the elements is 30

Copyright © 2018 Pearson Education, Ltd.


Averaging the Values in a List
# Create a list.
scores = [2.5, 7.3, 6.5, 4.0, 5.2]
# Create a variable to use as an accumulator.
total = 0.0
# Calculate the total of the list elements.
for value in scores:
total += value
# Calculate the average of the elements.
average = total / len(scores)
print('The average of the elements is', average)

The average of the elements is 5.3


Copyright © 2018 Pearson Education, Ltd.
total = 0
count = 0
while True :
inp = input('Enter a number: ')
if inp == 'done' : break Enter a number: 3
value = float(inp) Enter a number: 9
total = total + value Enter a number: 5
count = count + 1
Enter a number: done
average = total / count Average: 5.66666666667
print('Average:', average)

numlist = list()
while True :
inp = input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
numlist.append(value)

average = sum(numlist) / len(numlist)


print('Average:', average)
Two-Dimensional Lists
• Two-dimensional list: a list that contains
other lists as its elements
• Also known as nested list
• Common to think of two-dimensional lists as having
rows and columns
• Useful for working with multiple sets of data
• To process data in a two-dimensional list
need to use two indexes
• Typically use nested loops to process

Copyright © 2018 Pearson Education, Ltd.


Two-Dimensional Lists
(cont’d.)

Copyright © 2018 Pearson Education, Ltd.


Two-Dimensional Lists
(cont’d.)

Copyright © 2018 Pearson Education, Ltd.


Best Friends: Strings and Lists
>>> abc = 'With three words' >>> print(stuff)
>>> stuff = abc.split() ['With', 'three', 'words']
>>> print(stuff) >>> for w in stuff :
['With', 'three', 'words'] ... print(w)
>>> print(len(stuff)) ...
3 With
>>> print(stuff[0]) Three
With Words
>>>

Split breaks a string into parts and produces a list of strings. We think
of these as words. We can access a particular word or loop through
all the words.
>>> line = 'A lot of spaces'
>>> etc = line.split()
>>> print(etc)
['A', 'lot', 'of', 'spaces']
● When you do not
>>>
>>> line = 'first;second;third' specify a delimiter,
>>> thing = line.split()
>>> print(thing) multiple spaces are
['first;second;third']
treated like one
>>> print(len(thing))
1 delimiter
>>> thing = line.split(';')
>>> print(thing)
['first', 'second', 'third']
● You can specify what
>>> print(len(thing))
3 delimiter character to
>>>
use in the splitting
From [email protected] Thu Feb 27 09:14:16 2020

>>> line = 'From [email protected] Thu Feb 27 09:14:16


2020'
>>> words = line.split()
>>> print(words)
['From', '[email protected]', 'Thu', 'Feb', '27', '09:14:16',
'2020']
>>>
The Double Split Pattern
Sometimes we split a line one way, and then grab one of the
pieces of the line and split that piece again

From [email protected] Thu Feb 27 09:14:16 2020

words = line.split()
email = words[1]
print pieces[1]
The Double Split Pattern

From [email protected] Thu Feb 27 09:14:16 2020

words = line.split()
email = words[1] [email protected]
print pieces[1]
The Double Split Pattern

From [email protected] Thu Feb 27 09:14:16 2020

words = line.split()
email = words[1] [email protected]
pieces = email.split('@') ['alicihan.keles', 'hotmail.com']
The Double Split Pattern

From [email protected] Thu Feb 27 09:14:16 2020

words = line.split()
email = words[1] [email protected]
pieces = email.split('@’) ['alicihan.keles', 'hotmail.com']
print(pieces[1])
'hotmail.com'
Tuples
• Tuple: an immutable sequence
• Very similar to a list
• Once it is created it cannot be changed
• Format: tuple_name = (item1, item2)
• Tuples support operations as lists
• Subscript indexing for retrieving elements
• Methods such as index
• Built in functions such as len, min, max
• Slicing expressions
• The in, +, and * operators

Copyright © 2018 Pearson Education, Ltd.


Tuples
• To create a tuple with a single element (but you’re
probably not likely to do that too often), we have to
include the final comma, because without the final
comma, Python treats the (5) below as an integer in
parentheses:

>>> t=(5,)
>>> print(type(t))
<class 'tuple'>
>>> t=(5)
>>> print(type(t))
<class 'int'>
>>>

Copyright © 2018 Pearson Education, Ltd.


Tuples
my_tuple = (1, 2, 3, 4, 5)
print my_tuple
(1, 2, 3, 4, 5)

names = (‘Deniz’, ‘Duru’, ‘Derin’)


for n in names:
print (n)
OR
names = (‘Deniz’, ‘Duru’, ‘Derin’)
for i in range(len(names)):
print (names[i])

Deniz
Duru
Derin
Copyright © 2018 Pearson Education, Ltd.
Example
>>> julia = ("Julia", "Roberts", 1967, "Duplicity", 2009,
"Actress", "Atlanta, Georgia")
>>> print(julia[2])
1967
>>> print(julia[2:6])
(1967, 'Duplicity', 2009, 'Actress')
>>> print(len(julia))
7
>>> julia = julia[:3] + ("Eat Pray Love", 2010) + julia[5:]
>>> print(julia)
('Julia', 'Roberts', 1967, 'Eat Pray Love', 2010, 'Actress',
'Atlanta, Georgia')
>>>
Copyright © 2018 Pearson Education, Ltd.
Tuples Are Like Lists
Tuples are another kind of sequence that functions much like a list
- they have elements which are indexed starting at 0

>>> x = ('Gizem', 'Sinem’, 'Ali')


>>> for iter in y:
>>> print(x[2])
... print(iter)
Ali
...
>>> y = ( 1, 9, 2 )
1
>>> print(y)
9
(1, 9, 2)
2
>>> print(max(y))
>>>
9
but... Tuples are “immutable”
Unlike a list, once you create a tuple, you cannot alter its contents
- similar to a string

>>> z = (5, 4, 3)
>>> x = [9, 8, 7] >>> y = 'ABC' >>> z[2] = 0
>>> x[2] = 6 >>> y[2] = 'D' Traceback:'tuple' object
>>> print(x) Traceback:'str' object does does
>>>[9, 8, 6] not support item not support item
>>> Assignment Assignment
>>> >>>
Tuples (cont’d.)
• Tuples do not support the methods:
• append
• remove
• insert
• reverse
• sort

Copyright © 2018 Pearson Education, Ltd.


Things not to do With Tuples

>>> x = (3, 2, 1)
>>> x.sort()
Traceback:
AttributeError: 'tuple' object has no attribute 'sort'
>>> x.append(5)
Traceback:
AttributeError: 'tuple' object has no attribute 'append'
>>> x.reverse()
Traceback:
AttributeError: 'tuple' object has no attribute 'reverse'
>>>
Tuples (cont’d.)
• Advantages for using tuples over lists:
• Processing tuples is faster than processing
lists
• Tuples are safe
• Some operations in Python require use of
tuples
• list() function: converts tuple to list
• tuple() function: converts list to tuple

Copyright © 2018 Pearson Education, Ltd.


Tuples are More Efficient

• Since Python does not have to build tuple


structures to be modifiable, they are
simpler and more efficient in terms of
memory use and performance than lists
• So in our program when we are making
“temporary variables” we prefer tuples over
lists
Example
>>> my_tuple = (1, '2.3', 4, 'can', "istanbul", 3.14, """python""")
>>> print(my_tuple)
(1, '2.3', 4, 'can', 'istanbul', 3.14, 'python')
>>> list(my_tuple)
[1, '2.3', 4, 'can', 'istanbul', 3.14, 'python']
>>> a = list(my_tuple)
>>> print(a)
[1, '2.3', 4, 'can', 'istanbul', 3.14, 'python']
>>> print(a[1:5])
['2.3', 4, 'can', 'istanbul']
>>> tuple(a)
(1, '2.3', 4, 'can', 'istanbul', 3.14, 'python')
>>> b = tuple(a)
>>> print(b)
(1, '2.3', 4, 'can', 'istanbul', 3.14, 'python')
>>> print(b[2:6])
(4, 'can', 'istanbul', 3.14)
>>>

Copyright © 2018 Pearson Education, Ltd.


A Tale of Two Sequences

>>> l = list()
>>> dir(l)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort']

>>> t = tuple()
>>> dir(t)
['count', 'index']
Tuples and Assignment
• We can also put a tuple on the left-hand side of an
assignment statement
• We can even omit the parentheses

>>> (x, y) = (4, 'cihan')


>>> print(y)
cihan
>>> (a, b) = (99, 98)
>>> print(a)
99
Tuples are Comparable
The comparison operators work with tuples and other
sequences. If the first item is equal, Python goes on to the
next element, and so on, until it finds elements that differ.

>>> (0, 1, 2) < (5, 1, 2)


True
>>> (0, 1, 2000000) < (0, 3, 4)
True
>>> ('Cihan', 'Sinan') < ('Cihan', 'Sinem')
True
>>> ('Cihan', 'Sinan') > ('Ali', 'Sinem')
True
Sorting Lists of Tuples
• We can take advantage of the ability to sort a list of tuples
to get a sorted version of a dictionary
• First we sort the dictionary by the key using the items()
method and sorted() function

>>> d = {'a':10, 'b':1, 'c':22}


>>> d.items()
dict_items([('a', 10), ('c', 22), ('b', 1)])
>>> sorted(d.items())
[('a', 10), ('b', 1), ('c', 22)]
Plotting Data with
matplotlib
• The matplotlib package is a library for
creating two-dimensional charts and graphs.

• It is not part of the standard Python library,


so you will have to install it separately, after
you have installed Python on your system.

Copyright © 2018 Pearson Education, Ltd.


Plotting Data with
matplotlib
• To install matplotlib on a Windows system, open a
Command Prompt window and enter this command:
pip install matplotlib

• To install matplotlib on a Mac or Linux system,


open a Terminal window and enter this command:
sudo pip3 install matplotlib

• See Appendix F in your textbook for more


information about packages and the pip utility.

Copyright © 2018 Pearson Education, Ltd.


Plotting Data with
matplotlib
• To verify the package was installed, start IDLE and
enter this command:

>>> import matplotlib

• If you don't see any error messages, you can


assume the package was properly installed.

Copyright © 2018 Pearson Education, Ltd.


Plotting Data with
matplotlib
• The matplotlib package contains a module
named pyplot that you will need to import.
• Use the following import statement to
import the module and create an alias named
plt:

import matplotlib.pyplot as plt

For more information about the import statement, see Appendix E in your textbook.

Copyright © 2018 Pearson Education, Ltd.


Plotting a Line Graph with the
plot Function
• Use the plot function to create a line graph that
connects a series of points with straight lines.
• The line graph has a horizontal X axis, and a vertical
Y axis.
• Each point in the graph is located at a (X,Y)
coordinate.

Copyright © 2018 Pearson Education, Ltd.


Plotting a Line Graph with the
plot Function
Program 7-19 (line_graph1.py)
1 # This program displays a simple line graph.
2 import matplotlib.pyplot as plt
3
4 def main():
5 # Create lists with the X and Y coordinates of each data point.
6 x_coords = [0, 1, 2, 3, 4]
7 y_coords = [0, 3, 1, 5, 2]
8
9 # Build the line graph.
10 plt.plot(x_coords, y_coords)
11
12 # Display the line graph.
13 plt.show()
14
15 # Call the main function.
16 main()

Copyright © 2018 Pearson Education, Ltd.


Plotting a Line Graph with the
plot Function
• You can change the lower and upper limits of the X
and Y axes by calling the xlim and ylim functions.
Example:

plt.xlim(xmin=1, xmax=100)
plt.ylim(ymin=10, ymax=50)

• This code does the following:


• Causes the X axis to begin at 1 and end at 100
• Causes the Y axis to begin at 10 and end at 50

Copyright © 2018 Pearson Education, Ltd.


Plotting a Line Graph with the
plot Function
• You can customize each tick mark's label with the xticks
and yticks functions.
• These functions each take two lists as arguments.
• The first argument is a list of tick mark locations
• The second argument is a list of labels to display at the specified
locations.
plt.xticks([0, 1, 2, 3, 4],
['2016', '2017', '2018', '2019', '2020'])
plt.yticks([0, 1, 2, 3, 4, 5],
['$0m', '$1m', '$2m', '$3m', '$4m', '$5m'])

Copyright © 2018 Pearson Education, Ltd.


Program 7-24
1 # This program displays a simple line graph.
2 import matplotlib.pyplot as plt
3
4 def main():
5 # Create lists with the X,Y coordinates of each data point.
6 x_coords = [0, 1, 2, 3, 4]
7 y_coords = [0, 3, 1, 5, 2]
8
9 # Build the line graph.
10 plt.plot(x_coords, y_coords, marker='o')
11
12 # Add a title.
13 plt.title('Sales by Year')
14
15 # Add labels to the axes.
16 plt.xlabel('Year')
17 plt.ylabel('Sales')
18

Continued…
Copyright © 2018 Pearson Education, Ltd.
Program 7-24 (continued)
19 # Customize the tick marks.
20 plt.xticks([0, 1, 2, 3, 4],
21 ['2016', '2017', '2018', '2019', '2020'])
22 plt.yticks([0, 1, 2, 3, 4, 5],
23 ['$0m', '$1m', '$2m', '$3m', '$4m', '$5m'])
24
25 # Add a grid.
26 plt.grid(True)
27
28 # Display the line graph.
29 plt.show()
30
31 # Call the main function.
32 main()

Copyright © 2018 Pearson Education, Ltd.


Output of Program 7-24
Displayed by the
Displayed by the
title() function.
yticks() function.

Displayed by the
ylabel() function.

Displayed by the
xticks() function. Displayed by the
xlabel() function.
Copyright © 2018 Pearson Education, Ltd.
Plotting a Bar Chart
• Use the bar function in the
matplotlib.pyplot module to create a bar
chart.

• The function needs two lists: one with the X


coordinates of each bar's left edge, and another
with the heights of each bar, along the Y axis.

Copyright © 2018 Pearson Education, Ltd.


Plotting a Bar Chart

left_edges = [0, 10, 20, 30, 40]


heights = [100, 200, 300, 400, 500]

plt.bar(left_edges, heights)
plt.show()

Copyright © 2018 Pearson Education, Ltd.


Plotting a Bar Chart
• The default width of each bar in a bar graph is 0.8 along the X
axis.
• You can change the bar width by passing a third argument to
the bar function.

left_edges = [0, 10, 20, 30, 40]


heights = [100, 200, 300, 400, 500]
bar_width = 5

plt.bar(left_edges, heights, bar_width)


plt.show()

Copyright © 2018 Pearson Education, Ltd.


Plotting a Bar Chart
• The bar function has a color parameter that you
can use to change the colors of the bars.
• The argument that you pass into this parameter is a
tuple containing a series of color codes.

Color Code Corresponding Color


'b' Blue
'g' Green
'r' Red
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White

Copyright © 2018 Pearson Education, Ltd.


Plotting a Bar Chart
• Example of how to pass a tuple of color codes as a
keyword argument:

plt.bar(left_edges, heights, color=('r', 'g', 'b', 'w', 'k'))

• The colors of the bars in the resulting bar chart will


be as follows:
• The first bar will be red.
• The second bar will be green.
• The third bar will be blue.
• The fourth bar will be white.
• The fifth bar will be black.

Copyright © 2018 Pearson Education, Ltd.


Plotting a Bar Chart
• Use the xlabel and ylabel functions to add labels
to the X and Y axes.

• Use the xticks function to display custom tick mark


labels along the X axis

• Use the yticks function to display custom tick mark


labels along the Y axis.

Copyright © 2018 Pearson Education, Ltd.


Plotting a Pie Chart
• You use the pie function in the
matplotlib.pyplot module to create a pie chart.

• When you call the pie function, you pass a list of


values as an argument.
• The sum of the values will be used as the value of the whole.
• Each element in the list will become a slice in the pie chart.
• The size of a slice represents that element's value as a
percentage of the whole.

Copyright © 2018 Pearson Education, Ltd.


Plotting a Pie Chart
• Example

values = [20, 60, 80, 40]


plt.pie(values)
plt.show()

Copyright © 2018 Pearson Education, Ltd.


Plotting a Pie Chart
• The pie function has a labels parameter that you
can use to display labels for the slices in the pie
chart.
• The argument that you pass into this parameter is a
list containing the desired labels, as strings.

Copyright © 2018 Pearson Education, Ltd.


Plotting a Pie Chart
• Example
sales = [100, 400, 300, 600]
slice_labels = ['1st Qtr', '2nd Qtr', '3rd Qtr', '4th Qtr']
plt.pie(sales, labels=slice_labels)
plt.title('Sales by Quarter')
plt.show()

Copyright © 2018 Pearson Education, Ltd.


Plotting a Pie Chart
• The pie function automatically changes the color of
the slices, in the following order:
• blue, green, red, cyan, magenta, yellow, black, and white.

• You can specify a different set of colors, however,


by passing a tuple of color codes as an argument to
the pie function's colors parameter:
plt.pie(values, colors=('r', 'g', 'b', 'w', 'k'))

• When this statement executes, the colors of the slices in the resulting
pie chart will be red, green, blue, white, and black.

Copyright © 2018 Pearson Education, Ltd.


Summary
• This chapter covered:
• Lists, including:
• Repetition and concatenation operators
• Indexing
• Techniques for processing lists
• Slicing and copying lists
• List methods and built-in functions for lists
• Two-dimensional lists
• Tuples, including:
• Immutability
• Difference from and advantages over lists
• Plotting charts and graphs with the matplotlib Package

Copyright © 2018 Pearson Education, Ltd.


Acknowledgements / Contributions

These slides are Copyright 2010- Charles R. ...


Severance (www.dr-chuck.com) of the University
of Michigan School of Information and
open.umich.edu and made available under a
Creative Commons Attribution 4.0 License.
Please maintain this last slide in all copies of the
document to comply with the attribution
requirements of the license. If you make a
change, feel free to add your name and
organization to the list of contributors on this page
as you republish the materials.

Initial Development: Charles Severance,


University of Michigan School of Information

… Insert new Contributors and Translators here

You might also like