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

Lists and Tuples Part 1 - ch07 - Part1

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)
38 views

Lists and Tuples Part 1 - ch07 - Part1

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/ 27

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


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


Lists
• Keeping and organizing multiple items of data together;
Collection structures that allow easy access to these items later
by changing only the sequence numbers with a single name.

• List and tuple are examples of collection structures in Python.

• "list" is a collection that keeps multiple elements of the same or


different type together and allows adding, deleting and updating
operations on these elements.

• Each element in the list is arranged in a separate region in the


memory. The list variable points to the starting address of the
region where these elements are located.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-5
Introduction to Lists

Figure 7-1 A list of integers

Figure 7-2 A list of strings

Figure 7-3 A list holding different types

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


List Declaration
list1 = list() # creates an empty list.
list2 = [] # another way to create an empty list.

list3 = list([7, 4, 9, 233]) # creates a list with values


# 7,4,9,233 in it.
list4 = [7, 4, 9, 233] # another way to create a list with
# values 7,4,9,233 in it.

list5 = ["jane", "joe", "james"] # string list.


list6 = [8, 112, "jane", "john", 32.65] # a list of different
# types of elements.

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


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


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


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


Accessing List Elements
number_list = [10, 20, 30]
x = number_list[2]
print(x)
print(number_list[2])
# index numbers can be used to access list elements from
the end of the list,
# then the index number of the last element is -1.
y = number_list[-1]
z = number_list[-3]
print(y, z)

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


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


Assigning Lists
List variables carry the starting addresses of the sequential elements in
memory.
Therefore, list variables do not point directly to the values, but to the
address of the memory cell where the values are kept.
Variables that hold addresses are commonly referred to as reference
types.
Lists are also reference types.
If we want to copy a list to another list, it means that the memory address
in list1 is assigned to list2.
We can easily see that number_list1 and number_list2 point to the same
memory address with the identity function id().
number_list1 = [112, 65, 79]
number_list2 = number_list1
print(id(number_list1))
print(id(number_list2))
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 13
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 © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 14


len()
len() function finds the number of elements of a list.
This function is also used to find the character count of
Strings.
length = len(number_list)
print(length)

The last element of a list can be found as:


x = number_list[len(number_list) - 1]
print(x)

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


Operations with List Elements
number_list = [10, 20, 30]
for element in number_list:
print(element)

In the following loop, list elements are accessed using index numbers.
number_list = [10, 20, 30]
for i in range(0, len(number_list)):
print(number_list[i])

It is now possible to modify the list elements directly as shown in the loop
example above. E.g. list[i]*=2

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


Operations with List Elements
We can access elements in a certain range inside a list.
list[start:stop:step]
The start index is included in the range, the end index is
excluded.

number_list = [23, 82, 30, 112, 11, 66]


print(number_list[2:5:2])

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


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


List Slicing
If the starting index is not given in the list slicing operation,
the first index of the list which is 0 is accepted.
If no stop value is given, it goes to the end of the list.
If the increase amount is not given, the step is assumed to
be 1.
list[1:5] jumps 1 each from the element with index number 1
(2nd item) to element with index number 5 (6th item) (1
included, 5 excluded).
list[2:] includes the part from the index number 2 (3rd item) of
the list to the end.
list[:5] takes list items from the beginning of the list up to the
5th index number (6th item) (except 5).

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


List Slicing
Python returns empty list if given start index is greater than
stop index.

print(number_list[5:2])

However, if the step is given as a negative number in


addition to the above situation, the list will be handled in
reverse.

print(number_list[5:1:-1])

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


List Slicing
It is also possible to change elements together in a certain
range on lists.
For this, new values are assigned by selecting a certain part
of the list with the list slicing method.

number_list = [23, 82, 30, 112, 11, 66]


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

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


Concatenating (Merging) 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 22


Merging Lists
“+” operator is used to combine multiple lists.
number_list1 = [1, 2, 3]
number_list2 = [5, 4]
number_list3 = number_list1 + number_list2
print(number_list3)
If a single element is to be added to a list, this element must
also be a list.
number_list1 = [1, 2, 3]
number_list2 = number_list1 + [6]
print(number_list2)

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


List Methods and Useful Built-in
Functions (1 of 4)
• 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

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


List Methods and Useful Built-in
Functions (2 of 4)
• 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 25


List Methods and Useful Built-in
Functions (3 of 4)
Table 7-1 A few of the list methods

Method Description
append(item) Adds item to the end of the list.

index(item) Returns the index of the first element whose value is equal to item.
A ValueError exception is raised if item is not found in the list.
insert(index, item) Inserts item into the list at the specified index. When an item is inserted into a
list, the list is expanded in size to accommodate the new item. The item that
was previously at the specified index, and all the items after it, are shifted by
one position toward the end of the list. No exceptions will occur if you specify an
invalid index. If you specify an index beyond the end of the list, the item will be
added to the end of the list. If you use a negative index that specifies an invalid
position, the item will be inserted at the beginning of the list.
sort() Sorts the items in the list so they appear in ascending order (from the lowest
value to the highest value).
remove(item) Removes the first occurrence of item from the list. A ValueError exception
is raised if item is not found in the list.
reverse() Reverses the order of the items in the list.

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


List Methods and Useful Built-in
Functions (4 of 4)
• 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 © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 27

You might also like