Gaddis Python 4e Chapter 07 PPT - combinedForLesson4
Gaddis Python 4e Chapter 07 PPT - combinedForLesson4
Lists and
Tuples
• 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”?
$ 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
5
for i in [5, 4, 3, 2, 1] : 4
print(i) 3
print('Blastoff!') 2
1
Blastoff!
Lists and Definite Loops - Best Pals
Output_1: 10 20 30 40
Output_2: 40 30 20 10
A. [ ]
B. 3.14
C. False
D. "dog"
n_lst = lst[8]
print(lst)
print(n_lst)
print(len(alist))
print(len(alist[0]))
A. 2
B. 3
C. 4
D. 5
index = 0
while index < len(my_list):
print (my_list [index])
index += 1
Output:
10
20
30
40
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]
Output_1 : [1, 2, 3, 4, 5, 6, 7, 8 ]
list1 += list2
list1
Output_2: [1, 2, 3, 4, 5, 6, 7, 8 ]
print([1,2] + [3,4])
print(fruit + [6,7,8,9])
print([0] * 4)
•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]
>>> 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
print (numbers[:3])
[1, 2, 3]
print (numbers[2:])
[3, 4, 5]
print (numbers[:])
[1, 2, 3, 4, 5]
print(bio.index("Metatarsal"))
print(bio.index([]))
print(bio.index(43))
• 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"))
>>> 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
Output:
The list before the insert:
['James', 'Kathryn', 'Bill']
The list after the insert:
['Joe', 'James', 'Kathryn', 'Bill']
Output:
[ 9, 5, 0, 1, 89, 100, 3]
Sorted list: [ 0, 1, 3, 5, 9, 89, 100]
Output:
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
print("***".join(wds))
print("".join(wds))
However if;
list1 = [1, 2, 3, 4]
list2 = list1
both variables list1 and list2 will reference the same list in
memory.
numlist = list()
while True :
inp = input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
numlist.append(value)
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
words = line.split()
email = words[1]
print pieces[1]
The Double Split Pattern
words = line.split()
email = words[1] [email protected]
print pieces[1]
The Double Split Pattern
words = line.split()
email = words[1] [email protected]
pieces = email.split('@') ['alicihan.keles', 'hotmail.com']
The Double Split Pattern
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
>>> t=(5,)
>>> print(type(t))
<class 'tuple'>
>>> t=(5)
>>> print(type(t))
<class 'int'>
>>>
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
>>> 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
>>> 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
>>> 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
For more information about the import statement, see Appendix E in your textbook.
plt.xlim(xmin=1, xmax=100)
plt.ylim(ymin=10, ymax=50)
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()
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.
plt.bar(left_edges, heights)
plt.show()
• When this statement executes, the colors of the slices in the resulting
pie chart will be red, green, blue, white, and black.