Unit 6 - List, Tuples and Dictionary: Objectives
Unit 6 - List, Tuples and Dictionary: Objectives
Unit 6 - List, Tuples and Dictionary: Objectives
Objectives:
Students will learn the sequence data type objects in python like lists, tuple and dictionaries
Students can understand the difference between mutable and immutable objects
Students will learn how to access elements from the sequence type
Students will be dealing with list operators and functions
Students will be able to know about tuple operations like slicing and some built-in methods
Students can learn how to create a dictionary and implementation of all the sequence types
Module 1 - List
6.1 Definition
Python offers a range of compound data types often referred to as sequences. List is one of the most frequently used and
very versatile data types used in Python. Like a string, a list is a sequence of values. In a string, the values are characters;
in a list, they can be any type. The values in list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets and are separated
by commas. It can have any number of items and they may be of different types (integer, float, string etc.).
The first example is a list of four integers. The second is a list of three strings. The elements of a list don’t have to be
the same type. The following list contains a string, a float, an integer, and another list:
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
When we run the above program, we will get the following output:
e
p
Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list. When
the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned.
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers
[17, 5]
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.
6.7.2 list.extend()
extend takes a list as an argument and appends all of the elements
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print (t1)
['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified.
sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e']
6.7.3 list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert,
so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Deleting elements
6.7.4 list.remove(x)
Remove the first item from the list whose value is equal to x. It raises aValueError if there is no such item.
6.7.5 list.clear()
Remove all items from the list. Equivalent to del a[:].
print('List:', list)
6.7.6 list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the
last item in the list. (The square brackets around the I in the method signature denote that the parameter is optional, not
that you should type square brackets at that position. You will see this notation frequently in the Python Library
Reference.)
>>> t = [‘a’, ‘b’, ‘c’]
>>> x = t.pop(1)
>>> print (t)
[‘a’, ‘c’]
>>> print (x)
b
If you don’t need the removed value, you can use the del operator:
>>> t = [‘a’, ‘b’, ‘c’]
>>> del t[1]
>>> print (t)
[‘a’, ‘c’]
If you know the element you want to remove (but not the index), you can use remove:
>>> t = [‘a’, ‘b’, ‘c’]
>>> t.remove(‘b’)
>>> print (t)
[‘a’, ‘c’]
The return value from remove is None.
To remove more than one element, you can use del with a slice index:
>>> t = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
>>> del t[1:5]
>>> print (t)
[‘a’, ‘f’]
As usual, the slice selects all the elements up to, but not including, the second index.
Example:
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
6.7.7 list.count(x)
Return the number of times x appears in the list.
Example:
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# count element 'i'
count = vowels.count('i')
# print count
print('The count of i is:', count)
# count element 'p'
count = vowels.count('p')
# print count
print('The count of p is:', count)
6.7.10 list.copy()
Return a shallow copy of the list. Equivalent to a[:]
# mixed list
my_list = ['cat', 0, 6.7]
# copying a list
new_list = my_list.copy()
print('Copied List:', new_list)
Output:
Example:2
Output:1
Output:2
Example:3
Output:
Module 2 – Tuples
We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two
examples of sequence data types (Sequence Types — list, tuple, range). Since Python is an evolving language, other
sequence data types may be added. There is also another standard sequence data type: the tuple.
A tuple consists of a number of values separated by commas, for instance:
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may
be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part
of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create
tuples which contain mutable objects, such as lists.
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples
are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing
(or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and
are accessed by iterating over the list.
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate
these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following
a value with a comma. For example:
A tuple can also be created without using parentheses. This is known as tuple packing.
6.10 Access Tuple Elements
There are various ways in which we can access the elements of a tuple.
Indexing:
We can use the index operator [] to access an item in a tuple, where the index starts from 0. So, a tuple having 6 elements
will have indices from 0 to 5. Trying to access an index outside of the tuple index range (6,7,... in this example) will
raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
Negative Indexing:
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
Slicing:
We can access a range of items in a tuple by using the slicing operator colon:.
Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to
access a range, we need the index that will slice the portion from the tuple.
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a
tuple. Deleting a tuple entirely, however, is possible using the keyword del.
Example:1
Output:
Example:2
Output:
Module 3 -- Dictionaries
A dictionary is like a list, but more general. In a list, the index positions have to be integers; in a dictionary, the indices
can be (almost) any type.
You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each
key maps to a value. The association of a key and a value is called a key-value pair or sometimes an item.
As an example, we’ll build a dictionary that map from English to Spanish words, so the keys and the values are all
strings.
The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should
avoid using it as a variable name.
>>> eng2sp = dict()
>>> print (eng2sp)
{}
The curly brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use square brackets:
This line creates an item that maps from the key ’one’ to the value 'uno'. If we print the dictionary again, we see a key-
value pair with a colon between the key and value:
This output format is also an input format. For example, you can create a new dictionary with three items:
The order of the key-value pairs is not the same. In fact, if you type the same example on your computer, you might get
a different result. In general, the order of items in a dictionary is unpredictable.
But that’s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use
the keys to look up the corresponding values:
The key ’two’ always maps to the value 'dos' so the order of the items doesn’t matter.
If the key isn’t in the dictionary, you get an exception:
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other hand,
the get() method returns None if the key is not found.
Output:
Output:
6.18 Looping Techniques
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using
the items() method.
When looping through a sequence, the position index and corresponding value can be retrieved at the same time using
the enumerate() function.
To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.
Output:
Example:2
Output:
Example:3
Output:
Multiple Choice Questions
1. What will be the output of the following Python code?
>>>names = ['Amir', 'Bear', 'Charlton', 'Daman']
>>>print(names[-1][-1])
a) A
b) Daman
c) Error
d) n
2. Suppose list1 is [1, 3, 2], What is list1 * 2?
a) [2, 6, 4]
b) [1, 3, 2, 1, 3]
c) [1, 3, 2, 1, 3, 2]
d) [1, 3, 2, 3, 2, 1]
3. Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is:
a) [0, 1, 2, 3]
b) [0, 1, 2, 3, 4]
c) [0.0, 0.5, 1.0, 1.5]
d) [0.0, 0.5, 1.0, 1.5, 2.0]
4. To insert 5 to the third position in list1, we use which command?
a) list1.insert(3, 5)
b) list1.insert(2, 5)
c) list1.add(3, 5)
d) list1.append(3, 5)
5. Suppose t = (1, 2, 4, 3), which of the following is incorrect?
a) print(t[3])
b) t[3] = 45
c) print(max(t))
d) print(len(t))
6. What will be the output of the following Python code?
>>>t = (1, 2)
>>>2 * t
a) (1, 2, 1, 2)
b) [1, 2, 1, 2]
c) (1, 1, 2, 2)
d) [1, 1, 2, 2]
7. What will be the output of the following Python code?
>>>my_tuple = (1, 2, 3, 4)
>>>my_tuple.append( (5, 6, 7) )
>>>print len(my_tuple)
a) 1
b) 2
c) 5
d) Error
8. Which of these about a dictionary is false?
a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren’t ordered
d) Dictionaries are mutable
9. Which of the following is not a declaration of the dictionary?
a) {1: ‘A’, 2: ‘B’}
b) dict([[1,”A”],[2,”B”]])
c) {1,”A”,2”B”}
d) { }
10. What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
print(a.get(1,4))
a)1
b)A
c)4
d) Invalid syntax for get method
Descriptive Questions
1. What is list in python, explain it’s merits and demerits .
2. Can you explain tuple methods with suitable examples?
3. How can we create a dictionary and remove the item from it?
4. Write a python program to find second largest number in the given list.
5. Python Program to Generate Random Numbers from 1 to 20 and Append Them to the List
6. Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
7. Write a python program to multiply all the items in a dictionary.
8. Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that
Character