Lecture 4
Lecture 4
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
'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'
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 ([ ])
• 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
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]]
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
24
List Comprehension(cont):
• Let’s look at the second example:
• [x for x in range(1,20) if x%2==0 ]
• 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]
• 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