Unit IV material
UNIT IV: COMPOUND DATA
LISTS, TUPLES, DICTIONARIES
Content
Lists, list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters; Tuples, tuple assignment, tuple as return value; Dictionaries: operations and methods; advanced list processing - list comprehension, Illustrative programs: selection sort, insertion sort, merge sort, quick sort.
Objective
To use Python data structures –- lists, tuples, dictionaries
Outcome
Represent compound data using Python lists, tuples, dictionaries
4 COMPOUND DATA
Primitive data types are basic data types such as int, bool and float. Compound data is any data type which is constructed using primitive data types and other compound data types. Python offers different compound data types (sequences) such as lists, tuples and dictionaries.
A compound data type is one that holds multiple independent values.
Example
Create a compound data type to represent a point
in the cartesian coordinates.
A point
may be represented with a list, tuple, dictionary or a class in python.
4.1 LISTS
List is the collection (bag) of objects. We extensively use list to store and manipulate data in everyday computing.
A List is the built-in ordered sequence. A sequence is an iterable which supports efficient element access using integer indices via the getitem() special method and defines a len() method that returns the length of the sequence. Some built-in sequence types are list, str, tuple, and bytes.
Despite its name, list is more akin to an array in other languages than to a linked list since access to elements are O(1).
Examples
A list of web pages matching the keyword (google)
A list of friends (facebook)
A list of products prices (amazon)
A list of tasks to do
A list of grocery items to be purchased
A list of students enrolled in a class
The objects in the list can be of same type or of different types.
Example
Lists may be constructed in several ways:
Using a pair of square brackets to denote the empty list: []
Using square brackets, separating items with commas: [a], [a, b, c]
Using a list comprehension: [x for x in iterable]
Using the type constructor: list() or list(iterable)
4.1.1 LIST OPERATIONS
Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0.
repeat (*)
concatenate (+)
empty list
index
Exercises
What is the output for the following code?
What is the output for the following code?
4.1.2 LIST SLICES
We can select the specific subset from the list using slicing. We can either use a positive index (forward) or negative index(reverse) to refer the particular element or slice in the list.
A slice is an object usually containing a portion of a sequence. A slice is created using the subscript notation, [] with colons between numbers when several are given, such as in variable_name[1:3:5]. The bracket (subscript) notation uses slice objects internally.
mylist
12
48
12
72
34
21
Reverse index
-6
-5
-4
-3
-2
-1
Example
List may be sliced into part, from start
till end
.
mylist[start:end:step]
The elements are picked in steps from start
. If step is not mentioned, it is taken as 1 as default. The element at end
is not included.
Example
Slice can be passed as an object as well.
4.1.3 LIST METHODS
count(x)
return the number of times x appears in the list.
index(x)
return: the index of first occurence of x
insert(index,x)
insert an item at a given position(index).
list.append(x) Add an item to the end of the list; equivalent to a[len(a):] = [x].
list.extend(L) Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
list.remove(x) Remove the first item from the list whose value is x.
list.pop([i]) Remove the item at the given position in the list, and return it. If i
is not mentioned, the last element is popped out.
list.sort() Sort the items of the list in place
list.reverse() Reverse the elements of the list, in place.
Associated methods and attributes of a list may be viewed with dir(mylist)
.
Exercises:
What is the error in the following code?
What is the output of the following code?
4.1.4 LIST LOOP
List is the collection of iterable items. Using for
construct, you can process each element in the list. Do not add or remove an element from the list in its for
loop.
Example
Find the maximum number in the list
The in construct on its own is an easy way to test if an element appears in a list.
You can also use for/in to work on a str
ing type.
Range
The combination of the for-loop and the range() function allow you to build a traditional numeric for loop.
range(100)
creates a range
object, yielding the elements from 0 to 99 (excluding 100). range(5,10)
creates a range
object, yielding the elements from 5 to 9 (excluding 10). range(1, 100, 2)
yields odd numbers till 100.
The general syntax for range is range(start, stop, step)
while
Loop
while
LoopPython also has the standard while-loop, and the break and continue statements.
Exercise
Find the sum of N numbers (using List)
Create list with the following pattern for the input num:
Create list with the following pattern for the input num:
Write a function to find the factorial of ‘n’?
Find the sum of ‘n’ terms of the series
f = 0! + 1! + 2! + … + n! (n >= 0)
Find whether
n
is the factorial number
4.1.5 MUTABILITY
Everything is an object in python. Every object has an identity(id) and value(mutable or immutable). **Immutable **: The value of the object can not be changed.
Mutable objects can change their value but keep their id(). An immutable object has a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary.
For example, when a variable ‘num1’ is created, python allocates the memory location for the constant 72 and creates the unique identifier to refer that location. The variable num1 just refers to the memory location of the object 72.
When you assign another object to the same variable, it is saved in new location, without modifying the old object (72).
Thus the data is ‘immutable’ (not changeable or erasable). All datatypes in python such as int, bool, tuple are immutable.
Only exceptions are lists,sets and dictionaries, which are mutable (changeable). **Mutable **: The id of the object is the same even after the value is changed.
The effect of immutability:
a
is not altered, when b
is changed.
The effect of immutability:
a
is affected, when b
is changed.
4.1.6 Aliasing
If an object is referred by more than one variable name, it is aliased.
Assignment with lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory.
As list is mutable, a change by one reference is reflected in other reference, as both refer to the same list object.
Exercise
What is the output for the following code?
4.1.7 Cloning Lists
L.copy()
create a shallow copy of L
deepcopy
In shallow copy, the nested sublists are not cloned (same id). In deep copy, they are cloned (different id).
Exercise
Modify the program such that the addition to the
new_stock
won't change the elements inold_stock
.
4.1.8 List parameters
When the list is passed to a function as a parameter, the parameter refers to the same object (argument). Hence any change in the function gets reflected in the calling stack as well.
Example
ouput:
Write a function chop
that takes a list, modifies it by removing the first and last elements and returns None.
Useful links
Python Visualizer - http://pythontutor.com visualizes the program execution statement by statement.
Example: http://j.mp/greatestKG
Online Python interpreter - http://repl.it
Python inbuilt function documentation - http://j.mp/pythonDoc
Exercise
Write a function
cat_num
which takes a list, say,[1,2,3,4,5]
and modifies to[11,22,33,44,55]
(concatenates each element itself) and returns None.
Additional questions
What is the output of the following python code?
A list contains
n
elements (wheren
is a positive integer and0 > n > 10
. Write the necessary python code to produce a list that contains only the lastn-1
elements. Is there a version of the code that does not use anylist
methods whatsoever to achieve the same result?What is the value of
L
after you run the code below?
If
n
is the size of the list, and1 < k < n
, how will you find thek
th largest number in the list of numbers? (a #GTG challenge, a Google interview question).Complete the Hackerrank problem - https://www.hackerrank.com/challenges/python-lists
4.2 Tuples
List is the mutable sequence (append, remove, insert, pop, reverse, sort, extend and copy methods modify the list). Tuple is the immutable sequence. Only common methods for tuple and list are index() and count().
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
4.2.1 Tuple Assignment
Multiple variables can be assigned using tuple assignment (tuple unpacking). Parentheses are optional.
Exercise
What is the output for the following code
4.2.2 Tuple as a return value
Mutiple variables can be returned from the function using tuple. Parantheses are optional.
Exercise
Write the function
quotient_reminder
to return quotient and reminder ofa / b
4.3 Dictionaries
Lists and tuples are ordered sequence. The elements are accessed using index. Dictionary is the unordered sequence. The elements are accessed using key.
A dictionary is an associative array, where arbitrary keys are mapped to values. The keys can be any object with hash() and eq() methods. Called a hash in Perl.
4.3.1 Operations and methods
In dictionaries, the elements are stored as “key-value” pair. keys() return all the keys in the dictionary. values() return all the values in the dictionary.
The objects returned from dict.keys(), dict.values(), and dict.items() are called dictionary views. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. To force the dictionary view to become a full list use list(dictview).
All the items are iterable in dictionary. Each key shall be accessed using for
construct.
Example
Find the number of donors – blood group wise.
Output
Exercise
Write the function letters_freq to find the frequency of letters in a string. Return the result as the dictionary.
Find the capital for the given country from the imported dictionary
capital
in the format{capital: country}
.
Find the country for the given capital.
Find the countries for the given capitals.
Example: input = ['New Delhi', 'Washington DC'] output = ['India', 'US']
4.4 Advanced List Processing
4.4.1 List Comprehension
List comprehension is the pythonic way (one liner) to write the list loop. It gives the shorter and cleaner code.
This can be rewritten using list comprehension.
A list comprehension is the compact way to process all or part of the elements in a sequence and return a list with the results.
result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0]
generates a list of strings containing even hex numbers (0x..) in the range from 0 to 255. The if
clause is optional. If omitted, all elements in range(256) are processed.
Example
Find the sum of odd numbers in the list.
This can be written in one line using list comprehension.
Find the pass percentage
Example: Remove duplicates from the list (using dictionary)
4.5 Illustrative Programs
Select vs Insert vs Merge vs Quick
In selectsort, the position of the update is pre-determined, starting from the end of the list. We then go select the maximum value among the unsorted elements of the list, and swap it with the element in the pre-determined location.
In insertsort, given a key, a copy of a pre-determined element in the list, we insert it at the appropriate location after comparing it with the unsorted elements of the list.
In mergesort, a divide-and-conquer partitioning algorithm (which more often requires extra memory), the input array is divided in two halves, calls itself recursively for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves.
In quicksort, also a divide-and-conquer partitioning algorithm (lends itself to be efficiently implemented in-place without extra memory), the choice of the pivot element determines how the elements get partitioned, and calls itself recursively for the two partitions.
Sorting
Sorting is the arrangement of set in order
sorting a set of numbers
sorting a set of words
Sorting a set of numbers
Consider the list of prices of mobile phones of different brands (in thousands).
Now, we want to find the first three mobile phones with least prices. (Example: sort by price option in Amazon)
Question
Write the python code to display the price of first three items.
Sorting a set of words
Consider the set of new students joined in a program,
We want the computer to allot rollno
for each student. For this, we need to sort the list first.
After sorting,
Question
Write the python code to allot rollno
for each student.
Importance
Sorting is the essential part of computing. Sorting takes ~ 30% of all the computing time spent.
It is easier to
search
an item in the sorted set. Thus, sorting is the pre-requistie for the search algorithms.
4.5.1 Selection sort
In selection sort, select the minimum value from the unordered list and place it in the ordered list (index).
Exercises
Assume that first number in the list is minimum. Exchange, if first> second
Find the position of minimum element in the list (positionOfMin). Swap it with the element at the selected index 0.
Now, the first element is the minimum. Now, bring the next minimum value in the list as the second element. (index selected = 1)
If we continue to place the subsequent minimum values, we get the sorted list.
Before sorting
[12, 23, 15, 7, 3]
0
[12, 23, 15, 7, 3]
4
[3, 23, 15, 7, 12]
1
[3, 23, 15, 7, 12]
3
[3, 7, 15, 23, 12]
2
[3, 7, 15, 23, 12]
4
[3, 7, 12, 23, 15]
3
[3, 7, 12, 23, 15]
4
[3, 7, 12, 15, 23]
After sorting:
[3, 7, 12, 15, 23]
Algorithm
Select an index successively from 0 to N-1 where N = len(numbers)-1
Find the positionOfMin element in the list from index to N
Swap the element at index with that of positionOfMin, if index != positionOfMin
Pseudocode
Implementation
Output
4.5.2 Insertion sort
Exercises
Consider the second element in the list num. Swap, if second < first.
Take the third element. Insert it such that first three elements are in sorted order.
Insertion sort always maintains a sorted sublist in the lower positions of the list. Each new item is then “inserted” back into the previous sublist such that the sorted sublist is one item larger.
Pseudocode
Implementation
Output
Related Material
http://interactivepython.org/runestone/static/pythonds/SortSearch/TheInsertionSort.html
http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSort.html
http://bit.ly/insertVisualizer - insertSort in the visualizer
Exercises
Part 1 : https://www.hackerrank.com/challenges/insertionsort1
Part 2 : https://www.hackerrank.com/challenges/insertionsort2
Part 3 : https://www.hackerrank.com/challenges/correctness-invariant
4.5.3 Merge sort
It is divide recursively and conquer approach.
Exercises
Consider left and right lists of size 1. Merge them in a sorted order. Example:
Now consider the two sorted lists of unspecified size. Merge them in a sorted order. Example:
Divide the list
num
into left and right halves.
Algorithm
Divide the list recursively to left and right halves, till the partition size is 1
Merge the left and right halves in the sorted order
Algorithm for merge
Remove the minimum of two lists left and right and add it to the merged list till left or right becomes empty.
Append the remaining elements of left and right to merged list
Note: Both left and right are in sorted order, before merging.
Pseudo code
Implementation
Output
4.5.4 Quick Sort
Algorithm
Pick a random element as a pivot from the
num
listDivide
num
into small and large partitions which contain elements smaller or larger thanpivot
Recursively divide till partition size becomes 1
Pseudo code
Implementation
Exercises
Select last element of the list num as pivot.
Find from the front, which element is larger than or equal to pivot (
num[front]
). Find from the rear next to pivot, which element is smaller than pivot (num[rear]
) Swapnum[front]
andnum[rear]
iffront
<rear
Repeat step 2 till
front
<=rear
Now the first half of num holds values smaller than pivot. Second half of num excluding pivot holds vlaues larger than pivot. Now, front points to the start of the larger partition. Swap pivot and num[front]. to bring pivot to the middle. Example num = [12,3,17,45,15,12]
2 Mark Questions
Define list
Define tuple
What any four list methods and their use
What is compound data
How do you concatenate two lists
How do you reverse a list using slice.
What is immutable object
What are the mutable data types in python
Is a
str
ing object mutable?What is an alias. How do you create an alias for a list.
How do you clone a list
What is the risk in passing mutable objects such as list to a function.
What is the output of the following python code?
What is meant by tuple unpacking.
What are the ordered sequences in python
Define dictionary
How do you view all the keys of a dictionary.
What is list comprehension
What is the difference between selection sort and insertion sort.
What is divide-and-conquer algorithm. Give an example.
What is the difference between merge sort and quick sort.
Write a python code to display the sum of even numbers upto 100.
Write a function to find the
factorial
of N. (N!)What will happen, if an variable refering to an immutable object is assigned with a new value.
Write a function to count the number of occurances of a
key
element in alist
.
Part B Questions
Explain the use of different list methods with suitable examples.
Describe list comprehension with suitable examples.
Explain how selection sort algorithm works and implement the same in python.
Describe the insertion sort algorithm with python code.
Explain the merge sort algorithm and implement it in python.
Explain the quick sort algorithm and write the python code for the same.
Differentiate the data types list, tuple and dictionary with suitable examples.
Illustrate list loop and list mutability with suitable examples.
Differentiate aliasing and cloning of lists with examples.
Last updated