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

Lecture 4

The document provides an overview of lists and tuples in Python, explaining their structure, mutability, and various operations. Lists are mutable sequences that can contain items of different types, while tuples are immutable sequences. It also discusses list methods, list comprehension, and the differences between append and extend methods.

Uploaded by

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

Lecture 4

The document provides an overview of lists and tuples in Python, explaining their structure, mutability, and various operations. Lists are mutable sequences that can contain items of different types, while tuples are immutable sequences. It also discusses list methods, list comprehension, and the differences between append and extend methods.

Uploaded by

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

Pytho

Lists and Tuples

1
List and
Tuples:
• In many situations we organize data into a list - a shopping list,
a list of courses, a list of contacts on your cell phone, a list of
songs in your audio player, and so on
• In Python, lists are usually stored in a type of object called a
list
• A list is a sequence of objects
• The objects can be of any type- numbers, strings, even other
lists For example, here is how we would assign to the
variable pets the list of strings representing several pets
• pets = ['goldfish', 'cat', 'dog’]

2
List and Tuples(cont):
• In Python, a list is represented as a comma-separated
sequence of objects enclosed within square brackets
• An empty list is represented as []
• Lists can contain items of different types
• For example, the list named things, things = ['one', 2,
[3, 4]] has three items: the
first is string 'one', the second is integer 2, and the
third item is list [3, 4]
• List Operators
• Most of the string operators we have used can be used
on lists in similar ways
• For example, the items in the list may be accessed
individually using the indexing operator, just as individual
characters can be accessed in a string 3
List and Tuples(cont):
• pets[0] returns 'goldfish’ and
• pets[2] return 'dog’
• Negative indexes can be used too
• pets[-1] returns 'dog’

4
List and Tuples(cont):
• Following is a set of list operators and functions

• Try some of these,


• ‘x’ in [‘x’,’y’,’abc’] returns true
• [‘1’,’2’,’3’] + [1,2,3] returns [‘1’,’2’,’3’,1,2,3]
5
List and Tuples(cont):
• Like strings, lists can be “added,” meaning that they can be
concatenated
• They can also be “multiplied” by an integer k, which means
that k copies of the
list are concatenated
• pets + pets returns ['goldfish', 'cat', 'dog', 'goldfish', 'cat',
'dog’]
• pets * 2 returns ['goldfish', 'cat', 'dog', 'goldfish', 'cat', 'dog’]

• If you want to check whether string 'rabbit' is in the list, you


can use the in operator in a Boolean expression that evaluates
to True if string 'rabbit' appears in list pets

• 'rabbit' in pets returns False 6

• 'dog' in pets return True


List and Tuples(cont):
• Functions min(), max(), and sum(), which can take a list as input and
return the smallest item, the largest item, or the sum of the items,
respectively, in the list
• lst = [8, 12, 34, 120]
• min(lst) returns 8
• max(lst) returns 120
• sum(lst) returns 174
• Lists Are Mutable, Strings Are Not
• An important property of lists is that they are mutable
• What this means is that the content of a list can be changed
• For example, suppose that we want to be more specific about the
type of cat in list pets
• We would like pets[1] to evaluate to 'cymric cat' instead of just plain 7

'cat’
List and Tuples(cont):
To do this, we assign 'cymric cat' to pets[1]
pets[1] = ‘cymric cat’
pets returns ['goldfish', 'cymric cat', 'dog’]

So, the list no longer contains the string 'cat' at index 1; instead, it
contains the string 'cymric cat’
While lists are mutable, strings are not
What that means is that we cannot change the individual
characters of a string value
For example, suppose that we misspelled the type of cat
myCat = 'cymric bat'
8
List and Tuples(cont):
• Try to correct the mistake by changing the character at index 7 from 'b'
to a 'c’
• myCat[7] = ‘c’
• Traceback (most recent call last):
• File "<ipython-input-39-396d887ac518>", line 1, in <module>
• myCat[7] ='c'

• TypeError: 'str' object does not support item assignment


• The error message essentially says that individual characters (items) of
a
string cannot be changed (assigned to)
• Strings are immutable
• Does that mean that we are stuck with a misspelled value for myCat?
• We can simply reassign a brand-new value to variable myCat, i.e., 9

myCat =
List and Tuples(cont):
• In addition to lists, Python also supports tuples which, in many
ways, behave like lists except that tuples are immutable
• A tuple object contains a sequence of values separated by
commas and enclosed in parentheses (( )) instead of
brackets ([ ])

• days = ('Mo', 'Tu', 'We’)


• print(days) outputs (‘Mo’,’Tu’,’We’)

• The parentheses are optional in simple expressions like


this assignment
• days = 'Mo', 'Tu', 'We', 'Th’
• print(days) output ('Mo', 'Tu', 'We', 'Th’)
• My preference is with the brackets 10
List and Tuples(cont):
• The operators we used on lists can be used on tuples
• Example
• days = (‘Mo’,’Tu’,’We’)
• ‘Fr’ in days outputs False
• Concatenating on tuples
• days + (‘Th’,’Fr’,’Sa’,’Su’)
• outputs (‘Mo’,’Tu’,’We’,Th’,’Fr’,’Sa’,’Su’)
• Using index, we can access the elements of a tuple
• Example
• days[0]
• output ‘Mo’
• any attempt to change a tuple results in an error:
• days[4] = ‘xy’
• will result in an error 11
List and Tuples(cont):

• So, as in lists, items in tuples are ordered and can be accessed using an index (offset)
• Unlike lists, tuples are immutable: once a tuple is created, it cannot be changed
• Remember – With python, indexing starts at zero

• What about a one item tuple? Can we do this?

• Suppose we need to create a one-item tuple, such as


• days = ('Mo')
outputs
• Let’s evaluate the value and type of the object days:
'Mo’
• print(days)
• type(days) outputs <class 'str’>
• What happened? It appears the parenthesis were 12

ignored
List and Tuples(cont):
• Even if we used a numeric, the same would happen
• For example
• t = (3)
• print(t) outputs 3
• type(t)
• outputs int
• How do we create a one element tuple?
• What differentiates the parentheses in a general tuple from parentheses in
an expression is that enclosed in the tuple parentheses will be comma-
separated items
• So, the commas make the difference, and all we need to do is add a comma
after the first, and only, item to get a one-item tuple object:
• days = ('Mo’,)
• print(days) outputs
outputs tuple
(‘Mo’,)
• type(days) 13
List and Tuples methods:
• List and Tuple Methods
• We have seen functions that operate on lists such as, for example, the min() function:
• numbers = [6, 9, 4, 22]
• min(numbers)
• outputs 4

• In expression min(numbers), we say that function min() is called with one input
argument, the list numbers
• There are also functions called on lists
• For example, the append function
• Example
• lst =[‘a’,’b’,’c’]
• lst.append(‘d’) outputs [‘a’,’b’,’c’,’d’]
• We can do this again, lst.append[‘e’] outputs [‘a’,’b’,’c’,’d’,’e’]
14
List and Tuples methods(cont):
• Note how the way append was called

• For example
• lst.append(‘d’) should be interpreted as follows
• Apply the function append is called on the list with the input ‘d’
15
List and Tuples methods(cont):
• The effect of executing the statement lst.append(‘d') is
• that the input argument ‘d' is added at the end of list lst
• **Important**
• The function append() is a list function
• What this means is that function append() cannot be called on its own; it
always
has to be called on some list, lst, using the notation lst.append()
• We will refer to such functions as methods
• Another example of a list method is the count() method
• When called on a list with an input argument, it returns the number of times the
input argument appears in the list
• Example
• lst = [‘a’,’a’,’a’,’b’,’b’,’c’]
• lst.count(‘a’) outputs 3
16
List and Tuples methods(cont):
• The list method reverse() reverses the order of the objects
• Example
• lst = [1,2,3,4,5]
• lst.reverse()
• print(lst)
• outputs [5,4,3,2,1]
• You can view a listing of all list methods in the interactive shell using the help()
documentation function
• The sort() method sorts the items in the list in increasing order, using the
ordering that
“naturally” applies to the objects in the list
• Example
• pets =[‘dog’,’cat’,’goldfish’,’guinea pig’]
• pets.sort()
• pets
outputs ['cat', 'dog', 'goldfish', 'guinea pig’]

17
List and Tuples methods(cont):
• A list of numbers would be sorted using the usual increasing number order:
• lst = [4,2,8,5]
• lst.sort()
• lst outputs [2,4,5,8]
• If you want to sort descending, use lst.sort(reverse = True)
• lst.sort(reverse = True)
• lst outputs [8,5,4,2]

• Question: what happens if you try to sort a list with letters and numbers?
• lst = [‘a’,’b’,’c’,1,2,3]
• lst.sort() outputs an error

18
List and Tuples methods(cont):
• Class Exercise:
• What happens if you sort a list with numbers represented by strings?
• lst = [‘1’,’a’,’g’,’2’,’3’,’z’]
• Type lst.sort() and see what you get
• Try it again with lst =[’23’,’45’,’100’, ‘apple’,’pear’,’strawberry’]
• How is Python sorting the list?

• Example:
• Using the lst.insert() method?
• lst = [‘1’,’a’,’g’,’2’,’3’,’z’]
• Replace g with the t
• Now g occupied the second index of the lst
• lst.insert(2,”t”)
• g will be replaced with t 19
List and Tuples methods(cont):
• Extend method
• The method extend() appends the contents of a sequence to a list
• Syntax
• Following is the syntax for extend() method −
• list.extend(sequence)
• Parameters
• sequence − a list to add
• This method adds content to an existing list
• Example:
• List1 = [‘abc’,’123’]
• List2 = [4,5,6, ‘hello’];
• List1.extend(List2)
• print ("Extended List : ", List1 )
20
Append vs Extend:
• So, what is the difference between the methods extend and append
• append: Appends object at the end

• a = [1, 2, 3]
• a.append([4, 5])
• print (a)
• Output is [1, 2, 3, [4, 5]]

• extend: Extends list by appending elements from the iterable


• a = [1, 2, 3]
• a.extend([4, 5])
• print (a)
• Output is [1, 2, 3, 4, 5]
21
List Comprehension:
• List comprehension is powerful and must know the concept in Python
• Mastering this concept would help you in two ways

• You would start writing shorter and effective codes


• Hence, your code will execute faster
• List Comprehensions are 35% faster than FOR loop and 45% faster than map
function?
• Let’s look at some examples:

• 1. [x**2 for x in range(0,10)]


• 2. [x for x in range(1,20) if x%2==0 ]
• 3. [x for x in 'MATHEMATICS' if x in ['A','E','I','O','U']]

22
List Comprehension(cont):
• [x**2 for x in range(0,10)]

• This will output a list of the numbers squared from 0 to 9 (remember python
does include the number of the right)
• You can type [x**2 for x in range(0,10)] in your python console and run it

• Type list(range(0,10)) in your python console


• Without a list comprehension, how would you do this?
• You could use a for loop (I know we haven’t covered this yet)

• z =[] # initialize a blank list


• for j in range(0,10):
• z.append(j**2) # oh yes, indenting is important(that’s how python knows
that z.append(j**2) belongs to the loop)
23
List Comprehension(cont):
• If you are familiar with Python 2’s filter, map, reduce, lambda functions, you
could use the map function
• lambda functions are anonymous functions – don’t need to give them a name
• z = list(range(0,10))
• list(map(lambda x:x**2, a))

• lambda x:x**2 is an anonymous function which squares a number input


• Equivalent to
• def squared_num(x):
• return x**2

• In my opinion, list comprehension is easier to use

24
List Comprehension(cont):
• Let’s look at the second example:
• [x for x in range(1,20) if x%2==0 ]

• This will output numbers from 1 to 19 that are divisible by 2

• Try typing [x for x in range(1,20) if x%2==0 ] into your console and run it

• As an exercise you can try to do with it a loop and conditionals (we’ll cover this
later in the course)

• If you were using Python 2, we would need to use the filter function

• z = list(range(1,20))
• list(filter(lambda x: x%2,z))
25
List Comprehension(cont):
• Last example:
• [x for x in 'MATHEMATICS' if x in ['A','E','I','O','U’]]
• This will output all the vowels (you remember the song for vowels right?,
a,e,i,o,u and sometimes y ) in the word ‘MATHEMATICS’
• Type [x for x in 'MATHEMATICS' if x in ['A','E','I','O','U’]] in your python
console

• Homework exercise, try doing with filter or with a loop and if conditional (you
can wait until we cover loops in the course)

26
List Comprehension(cont):

• Class Exercise:
• What does this list comprehension output?
• [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2
 == z**2]

• Remember , Pythagorean theorem?


• x**2 + y**2 = z**2 (sides of a right-angled triangle?)

• Output will be the set of Pythagorean triples for integers between 1 and 30
27
List Comprehension(cont):
• Solution to the exercise
• Run the code in your console
• [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2
== z**2]

28
List Comprehension(cont):
Before going to the quiz, I want to present a method that you will most likely use
with lists and it’s called the pop() method
The pop() method removes the item at the given index from the list and returns the
removed item
The syntax of the pop() method is:
list.pop(index)

Example:
myarray=[1,2,3,4,5]
myarray.pop()
output is 5
print(myarray)
If no index is provided, pop() will remove the last element in the list and the list is
changed 29
List Comprehension(cont):
Example

myarray = [1,2,3,4,5,6,7,8]

print(myarray.pop(0))
print(myarray.pop(1))
print(myarray.pop(2))
print(myarray)

30

You might also like