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

Lists and Tuples Part 2 - ch07 - Part2

Python study guide

Uploaded by

sanananashaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lists and Tuples Part 2 - ch07 - Part2

Python study guide

Uploaded by

sanananashaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Starting out with Python

Fifth Edition, Global Edition

Chapter 7
Lists and Tuples

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-1


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-2


Topics (2 of 2)
• Copying Lists
• Processing Lists
• List Comprehensions
• Two-Dimensional Lists
• Tuples
• Plotting List Data with the matplotlib Package

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-3


List Methods

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-4


append() and insert()
There are different ways to add elements to lists.
append() and insert() methods are the two of them.
append() is used to add the specified element to the
end of a list.

number_list = [112, 79, 65]


number_list.append(80)
print(number_list)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-5


append() and insert()
insert() is used to add an element into the specified
index of a list.

number_list = [112, 79, 65]


number_list.insert(1, 40)
print(number_list)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-6


remove(), del and pop()
remove(), del and pop methods are used to remove
elements from a list.
remove() is used to remove the specified value from a list.
number_list = [112, 79, 65]
number_list.remove(79)
print(number_list)

If the same value occurs more than once in the list, only the
first one is deleted.
number_list = [121, 79, 65, 121, 79, 65]
number_list.remove(79)
print(number_list)
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-7
remove(), del and pop()
The del method is used to delete an entire list or an
element at a specific index.
number_list = [112, 79, 65]
del number_list[2]
print(number_list)

del number_list # in this case the list variable is


completely destroyed.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-8


remove(), del and pop()
pop() method is used in two different ways.
In the first use case, the parentheses following the pop
are empty, this allows to take the last element of the list,
transfer it to a variable and delete this element from the
list.

number_list = [112, 79, 65]


a = number_list.pop()
print(a)
print(number_list)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-9


remove(), del and pop()
In the second usage, an element at a certain index of
the list can also be removed with the pop() method.

number_list = [112, 79, 65]


a = number_list.pop(1)
print(a)
print(number_list)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 10


Items of a List
index()
index(), this method allows us to find the index of any
element in the list.
If the element is not in the list, it generates an error
known as ValueError.
If the same value is found more than once in the list, the
index() command returns only the index of the first
value.

number_list = [112, 79, 65]


index = number_list.index(79)
print(index)
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 11
index()
It is also possible to search from a specific index with
the index() method.
The first expression in the index() indicates the value to
be searched, and the second expression indicates the
index from which to start the search.

number_list = [112, 79, 65, 112, 79, 65]


index = number_list.index(79, 2)
print(index)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 12


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 13


Copying Lists

Figure 7-5 list1 and list2 reference the same list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 14


Copying Lists
Assigning one list to another with the = operator does not
mean copying the list.
The values of the list are still kept in one place in memory,
what is copied is just the address information.
To create a new copy of the values in a list and assign it to a
new list, the elements of the first list must be copied one by
one into the second list.
number_list1 = [112, 65, 79]
number_list2 = number_list1[:] # By slicing number_list1, it
is ensured that each element is assigned to number_list2
one by one.
In this case, a copy of the elements in number_list1, not the
address, is assigned to number_list2.
print(id(number_list1))
print(id(number_list2))
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 15
Copying Lists
It is also possible to copy only a part of them when
copying lists.

number_list1 = [112, 65, 79, 90, 60, 70]


number_list2 = number_list1[1:4]
print(number_list2)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 16


sort()
sort() method is used to sort a list from smallest to largest.
number_list = [112, 65, 79, 90, 60, 70]
number_list.sort()
print(number_list)

With the sort(), character-based lists can be sorted, as well


as numerical lists. In this case, the sorting is done from a to
z.
word_list = ["abz", "vyz", "def", "qwx"]
word_list.sort()
print(word_list)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 17


reverse()
reverse() method is used to reverse the current element
order of a list.
The point here is that the reverse() command does not
sort from largest to smallest, it just reverses the current
order of the list.

number_list = [112, 65, 79, 90, 60, 90]


number_list.reverse()
print(number_list)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 18


reverse()
For sorting from largest to smallest, first the sort()
method is executed, then it is followed by the reverse()
method.

number_list = [112, 65, 79, 90, 60, 70]


number_list.sort()
number_list.reverse()
print(number_list)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 19


count()
count() method is used to find how many times an
element is repeated in the list.

number_list = [112, 65, 79, 90, 60, 60]


i = number_list.count(60)
print(i)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 20


max() and min()
max() method is used to find the largest element of a
list, and min() method is used to find the smallest.

number_list = [112, 65, 79, 90, 60, 70]


nmax = max(number_list)
nmin = min(number_list)
print("Maximum=", nmax, "Minimum=", nmin)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 21


max() and min()
max() and min() methods also operate on character-
based lists and return the largest or smallest element of
the list in alphabetical order.

word_list = ["mis", "cmpe", "art"]


nmax = max(word_list)
nmin = min(word_list)
print("largest item=", nmax, "smallest item=", nmin)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 22


sum()
sum() method is used to find the sum of the elements of
a numeric list.

number_list = [112, 65, 79, 90, 60, 70]


total = sum(number_list)
print(total)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 23


Processing Lists (1 of 2)
• 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)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 24


Processing Lists (2 of 2)
• A function can return a reference to a list
• To save the contents of a list to a file:
– Use the file object’s writelines method
 Does not automatically write \n at then end of each item
– Use a for loop to write each element and \n
• To read data from a file use the file object’s
readlines method

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 25


List Comprehensions (1 of 7)
• List comprehension: a concise expression that creates
a new list by iterating over the elements of an existing
list.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 26


List Comprehensions (2 of 7)
• The following code uses a for loop to make a copy of
a list:
list1 = [1, 2, 3, 4]
list2 = []

for item in list1:


list2.append(item)

• The following code uses a list comprehension to make


a copy of a list:
list1 = [1, 2, 3, 4]
list2 = [item for item in list1]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 27


List Comprehensions (3 of 7)

• The iteration expression works like a for loop


• In this example, it iterates over the elements of list1
• Each time it iterates, the target variable item is
assigned the value of an element.
• At the end of each iteration, the value of the result
expression is appended to the new list.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 28


List Comprehensions (4 of 7)

list1 = [1, 2, 3, 4]
list2 = [item**2 for item in list1]

• After this code executes, list2 will contain the values


[1, 4, 9, 16]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 29


List Comprehensions (5 of 7)

str_list = ['Winken', 'Blinken', 'Nod']


len_list = [len(s) for s in str_list]

• After this code executes, len_list will contain the


values [6, 7, 3]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 30


List Comprehensions (6 of 7)
• You can use an if clause in a list comprehension to select
only certain elements when processing a list
list1 = [1, 12, 2, 20, 3, 15, 4]
list2 = []

for n in list1:
if n < 10:
list2.append(n)

Works the same as…

list1 = [1, 12, 2, 20, 3, 15, 4]


list2 = [item for item in list1 if item < 10]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 31


List Comprehensions (7 of 7)

list1 = [1, 12, 2, 20, 3, 15, 4]


list2 = [item for item in list1 if item < 10]

• After this code executes, list2 will contain [1, 2, 3,


4]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 32


Two-Dimensional Lists (1 of 3)
• 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 33


Two-Dimensional Lists (2 of 3)

Figure 7-8 A two-dimensional list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 34


Two-Dimensional Lists (3 of 3)

Figure 7-10 Subscripts for each element of the scores list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 35


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 36


Tuples
• Tuples do not support the methods:
– append
– remove
– insert
– reverse
– sort

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 37


Tuples
• 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 38


Tuples
Tuples are very similar to lists, but the only difference is that
after they are created, operations such as adding, deleting,
changing, sorting cannot be performed on them.
number_tuple = (7, 12, 63)
a = number_tuple[1]
print(a)
len() command is also used in tuples to find the number of
elements.
number_tuple = (7, 12, 63)
length = len(number_tuple)
print(length)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 39


Tuples

number_tuple = (7, 12, 63)


print(number_tuple)

number_tuple = (7, 12, 63)


for x in number_tuple:
print(x)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 40


Tuples
Again using the for loop, tuple elements can be
accessed by their indices.
number_tuple = (7, 12, 63)
for x in range(len(number_tuple)):
print(number_tuple[x])

Slicing can be done in the same way as with lists.


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

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 41


Tuples
in, not in, and index() method are used to check for element
presence in a tuple.
number_tuple = (1, 2, 3, 4, 5)
print(2 in number_tuple)
print(6 not in number_tuple)
print(number_tuple.index(5))
count() method is used to find the number of times an
element occurs in a tuple.
number_tuple = (1, 3, 3, 2, 3, 4, 2, 5)
i = number_tuple.count(3)
print(i)
print(number_tuple.count(3))

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 42


Tuples

number_tuple = (1, 3, 3, 2, 3, 4, 2, 5)
nmax = max(number_tuple)
nmin = min(number_tuple)
print("largest item:", nmax, "smallest item:", nmin)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 43


Tuples

number_tuple = (1, 3, 3, 2, 3, 4, 2, 5)
total = sum(number_tuple)
print(total)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 44


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 © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 45

You might also like