List, Tuples and Dictionary
List, Tuples and Dictionary
List, Tuples and Dictionary
A list is a data type that can be used to store any type and number of variables and
information. Other important sequence types used in Python include lists. A sequence type is
formed by putting together some other types in a sequence. Here is how we form lists
You can define and assign items to a list with the expression:
my_list = []
>>> colorlist=[‘Red’,’Green’,’blue’,’Yellow’,’Black’]
>>> numberlist=[1,2,3,4,5,6,7,8,9,10]
>>> mixlist=[1,2,'Hello','Class']
Another type of list can be declare that list is list in the list called nested list in this list we have a list
like number list[1,2,3,4,5] and if this number list has another list within the list is called nested list
Example
nestedlist=[1,2,[3,4,5,6],7,8,9,10]
This list is nested the element 3,4,5,6 are be accessed with the single subscript or address.
>>>print(nestedlist[2])
[3,3,4,5]
If you want to access the single element of the nested list then you have you give subscript
within the subscript
Example
>>>print(nestedlist[2][2])
5
In this example two subscript has given first subscript is for the outer list and second is for
inner list the nestedlist element 2 will first and then if element 2 is a list then the second
subscript element comes into the picture and the inner list has the access of 2nd element and
that element is 5.
Append()
You can update single or multiple elements of lists by giving the slice on the left-hand side
of the assignment operator, and you can add to elements in a list with the append() method.
>>>list.append(item)
Example
colorlist.append(‘Voliet’)
append() can also be used to insert another list into the list
Example
>>>a=[1,2,3]
>>>b=[‘a’,’b’,’c’]
>>>a.append(b)
Append() will always insert item at the end like in the example give above violet color is
added in the list at the end of the list and also the list a is appended by list b so list b is
inserted at the end of list a.
Insert()
If you want to insert any item at a desired location so you have to use insert() method in
palace of append() method. Append() will always insert item at the end of list but with
insert() item will inserted at a particular place or index.
>>>list.insert(index, item)
Example
Colorlist.insert(4,’White’)
Just like append() insert() can also be use to insert another list in the list.
As you have seen in the example given above that the white is inserted at the 4th index of
the list because list by default starts with 0 so index 4 is at the 5th place of the list. And the
vales of b list has inserted at the 1st index which is actually the 2nd place of the list
Remove()
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know.
>>>list.remove(item)
Example
>>>colorlist.remove(‘Yellow’)
In the above example yellow has removed from the list with remove(). We can use pop() and
del() functions for removing the elements from the list.pop and del is use to remove the
element by value but remove() is to remove with index.
Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string. In fact, lists respond to
all of the general sequence operations we used on strings in the prior chapter.
>>>len(colorlist)
because it start counting from 1 but the subscript of the list start with 0.
Example
>>>len(colorlist+numberlist)
15
Because colorlist has 5 and numberlist has 10 items so when both the lists are added.
If plus (+) operator used with numbers it add two numbers if we use it with list it used for
concatenation means joining two string or lists.
Example
>>>print(colorlist+numberlist)
[‘Red’,’Blue’,’White’,’Black’,’Yellow’,1,2,3,4,5,6,7,8,9,10]
As the multiplication is done with multiply (*) operator to the number similarly with the
list it can be repeated that much time which are given
Example
>>>print(numberlist * 2)
[1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10]
The will repeat itself two times because the multiplication is done by 2 if you multiply it
by 4it will repeat four times.
There is another function of list is seraching any element is the memer of the list or not it
just give you a true if the element is in the list else false.
Example
If we search 3 in the colorlist then the result will be false because colorlist have only the
names of the colors. But if we search 3 in the numberlist then the result will be true
because it contain 3 as a member of the list.
Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings. You can also slice lists as you have access the values of the list with the subscript of
the list.
>>>colorlist[0]
Red
Example
>>>print(colorlist[4])
Yellow
Example, if you only want to display the three colors from 2 to 5
>>>colorlist[2:5]
[‘Blue’,’Black’,’Yellow’]
it will display the 3rd 4th and 5th item of the list.
The list, tuple and string all works same with the subscripts, the first item is always starts
with 0 and the last item will be n-1 if the size of the list is n.
And there is negative representation of the subscript it always starts at the last item of the
list and the subscript starts with -1 and it move towards the first item of the list and decrease
subscript like -2,-3,-4 and so on.
Example
>>>print(colorlist[-1])
Black
because in case of negative subscript it starts from last element, colorlist has 5 elements and
it starts with
>>>print(colorlist[-4])
Green
Let us take an example to find the maximum, minimum and mean from a list.
In the above example an empty list has created and with help of the input function user
will enter the number of elements of the list. While loop will control the number of inputs
entered by the user and insert those values in the list with the append function. When
the list has completed then we are able to find the maximum minimum and average from
the list with the help built-in functions of list like max() and min() we can find it and for
average we have to use two built-in function sum() to find the sum of all the elements of
the list and with len() function we will find the number of elements of the list. With sum()
and len() we can easily find the average of the list.
Linear search is a searing technique to search any element from the list. In this technique a
list is there with some elements and then user will enter a number for search in the listit will
check every element one by one linearly or sequentially. If the number found it will return
number found otherwise number not found.
Output of linear search is
Matrix implementation using list
We can implement matrix operation using list. Matrix operation can be implemented using
nested list. List inside another list is called nested list.
Example
Write a program to input any matrix with mXn, and print the number on the output screen in
matrix format.
Matrix creation
Program 1
Output
There is another way to create matrix nested matrix without random function.
Program 2
A=[]
for i in range(n):
for j in range(n):
print(A)
for i in range(n):
for j in range(n):
print()
B=[]
for i in range(n):
row=[] #temporary list to store the row
for j in range(n):
print(B)
for i in range(n):
for j in range(n):
Output
123
456
789
987
654
321
Matrix Addition
Write a program to input any two matrices and print sum of matrices.
Program 1
A=[]
for i in range(n):
for j in range(n):
print(A)
for i in range(n):
for j in range(n):
print()
B=[]
for i in range(n):
for j in range(n):
print(B)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in range(n):
for j in range(n):
for i in range(n):
for j in range(len(A[0])):
for r in result:
Output
>>>
5
6
123
456
789
987
654
321
We can write addition of two matrix program with another method with random function
Program 2
Output
Matrix Multiplication
Write a program to input any two matrices and print product of matrices.
Output
Diagonals of a matrix
Write a program to input any matrix and print both diagonal values of the matrix.
Output
Tuple
A Tuple is a collection of Python objects separated by commas, or you can say 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. Creating a tuple is as simple as putting
different comma-separated values. Optionally you can put these comma-separated values
between parentheses also.
>>>tuplename=(element1,element2,….)
Example
Tuplecolor=(‘Red’,’Green’,’Blue’,’Yellow’,’Black’)
This is how we can create a string tuple, we can also create number tuple
Example
tuplenumber=(1,2,3,4,5,6,7,8,9,10)
A mix tuple mix means both the number and character are there in the list
Example
Tuplemix=(‘Hello’,’Class’,1,2,3)
If you want to declare an empty tuple you simply need to write parentheses “()” without any
value.
Example
Tupleempty=()
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple
elements. But you can create a new tuple with the existing tuples
Example
>>>len(tuplenumber)
10
because it start counting from 1 but the subscript of the tuple start with 0.
Example
>>>len(tuplecolor+tuplenumber)
15
Because tuplecolor has 5 and tuplenumber has 10 items so when both the tuples are
added.
If plus (+) operator used with numbers it add two numbers if we use it with tuple it used
for concatenation means joining two string or tuples.
Example
>>>print(tuplecolor+tuplenumber)
[‘Red’,’Blue’,’White’,’Black’,’Yellow’,1,2,3,4,5,6,7,8,9,10]
As the multiplication is done with multiply (*) operator to the number similarly with the
list it can be repeated that much time which are given
Example
>>>print(numberlist * 2)
(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10)
The will repeat itself two times because the multiplication is done by 2 if you multiply it
by 4 it will repeat four times.
In expression is to use to find weather the given element is in the tuple or not.
Output
In this example two tuple and a list has been created one tuple is color, one tuple is
number and a number list. print will show the list and tuple elements. Lenth efunction
will return the number of elements of the numbertuple. Max() will return the hignest
value in the tuple and tat is ‘Yellow’ because yellow has the highest ASCII value compared
to others elements of the tuple. And min() will return the minimum value of the tuple
that is ‘Black’ because first two character of ‘blue’ and ‘black’ are same but the third
charter of ‘black’ is ‘a’ and ‘blue’ is ‘u’ so ‘a’ has lower ASCII than ‘u’ so black will be
smallest element of the tuple. And tuple() will convert ant list into tuple as the
numberlist is list and with the help of tuple function it will converted into tuple
Example
Output
In the above example with the tuple function en empty tuple has created and then the
empty tuple is concatenated with the sting ‘PYTHON’ with plus(+) operator. The
statement t=t+(‘PYTHON’,) is use to concatenate and store the change in the tuple itself.
String ‘PYTHON’ is the single element of the tuple so the length of the tuple is 1 only.
Another tuple t1 has created with 3 elements because every element of the tuple is
seprated by comma, so t1 has three length.
Example
Let us take an example of swapping two tuples without using third tuple:
Output
Dictionary
A dictionary is like a list but instead of looking up an index to access values, you’ll be using a
unique key, which can be a number, string, or tuple. Dictionary values can be anything but
the keys must be an immutable data type. Each key is separated from its value by a colon
(:), the items are separated by commas, and the whole thing is enclosed in curly braces { }.
An empty dictionary without any items is written with just two curly braces, like this: {}.
Here is the syntax of dictionary structure: dictionary = {key_1 : a, key_2 : 2, key_3 : ab}
Let us take an example of taking input from the use and store them in the dictionary and then
use it to get desired output.
Output
We have created a empty dictionary with the function dict() naming menu and user will enter
the number of elements of the dictionary. With the help of while loop user will enter the
name of the item in the menu and the price of that item. And that will store in the
dictionary. Then with the help of for loop we can access the elements of the dictionary.
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing
entry, or deleting an existing entry. The syntax of adding any item is: dictionary [“new key”
]= Value like
>>>ditem[“Cold Coffee”]=50.
You might want to change the values in any of the keys at one point. For instance, you need
to change the price of “Cold Drink” from 35 to 45. The Syntex for updating any value
dictionary [“Existing key”]= Value like
>>>ditem[“Cold Drink”] = 45
Delete Dictionary Elements
Assuming you no longer want to include spam in your menu, you can easily do so with the del
method. Syntax is del dictionary[‘item’].If you want to remove all entries in the dictionary,
you can use the method dictionary.clear().To clear all entries in the menu:
>>>ditem.clear(menu)
The Python Shell displayed an empty dictionary with the clear command. Now that it contains
no data at all, you might decide to delete the dictionary. You can do so with the del method:
del dictionary.
Copy() function creates the copy of ditem dictionary. Item() function shows the all the
item of the in the dictionary. Keys() function will only show the keys of the dictionary.
Just like keys() values() function is also use to show only the values associated with
different keys of the dictionary
Sorting algorithm
Sorting is any process of arranging items systematically, and has two common, yet distinct
meanings: ordering: arranging items in a sequence ordered by some criterion; categorizing:
grouping items with similar properties.
we can distinguish two types of sorting. If the number of objects is small enough to fits into
the main memory, sorting is called internal sorting. If the number of objects is so large that
some of them reside on external storage during the sort, it is called external sorting.
Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in
form of an list with n number of elements. Bubble Sort compares all the element one by one
and sort them based on their values.
If the given array has to be sorted in ascending order, then bubble sort will start by
comparing the first element of the array with the second element, if the first element is
greater than the second element, it will swap both the elements, and then move on to
compare the second and the third element, and so on.
If we have total n elements, then we need to repeat this process for n-1 times.
It is known as bubble sort, because with every complete iteration the largest element in the
given array, bubbles up towards the last place or the highest index, just like a water bubble
rises up to the water surface.
Sorting takes place by stepping through all the elements one-by-one and comparing it with
the adjacent element and swapping them if required.
Following are the steps involved in bubble sort(for sorting a given array in ascending order):
Starting with the first element(index = 0), compare the current element with the next
element of the array.
If the current element is greater than the next element of the array, swap them.
If the current element is less than the next element, move to the next
element. Repeat Step 1.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
since 5 > 1.( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap
since 5 > 2.( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 >
5), algorithm does not swap them.
Second Pass:
Third Pass:
Insertion sort
Insertion sort is based on the idea that one element from the input elements is consumed in
each iteration to find its correct position i.e, the position to which it belongs in a sorted
array.
It iterates the input elements by growing the sorted array at each iteration. It compares the
current element with the largest value in the sorted array. If the current element is greater,
then it leaves the element in its place and moves on to the next element else it finds its
correct position in the sorted array and moves it to that position. This is done by shifting all
the elements, which are larger than the current element, in the sorted array to one position
ahead
The second element of an array is compared with the element that appears before it
(only first element in this case). If the second element is smaller than first element,
second element is inserted in the position of first element. After first step, first two
elements of an array will be sorted.
The third element of an array is compared with the element that appears before it
(first and second element). If third element is smaller than first element, it is inserted
in the position of first element. If third element is larger than first element but,
smaller than second element, it is inserted in the position of second element. If third
element is larger than both the elements, it is kept in the position as it is. After
second step, first three elements of an array will be sorted.
Similarly, the fourth element of an array is compared with the elements that appears
before it (first, second and third element) and the same procedure is applied and that
element is inserted in the proper position. After third step, first four elements of an
array will be sorted.
Example
Let us loop for i = 1 (second element of the array) to 5 (Size of input array)
i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12, 11, 12, 13, 5, 6.
i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13,11,
12,13,5,6.
i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one
position ahead of their current position 5, 11, 12, 13, 6.
i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position
ahead of their current position 5, 6, 11, 12, 13
Summery
A list is a data type that can be used to store any type and number of variables and
information, it is editable in nature.
List can update be by using append()and insert()method.
List items can be removed by remove() and del method.
List have different functions like len(), concatenate( + ),repetition( * ), membership,
iteration, min(), max(), cmp(), list().
A Tuple is a collection of Python objects which is immutable in nature.
Tuples cannot be updated they only be deleted using del method.
Like list tuple have different function len(), concatenate( + ),repetition( * ),
membership, iteration, min(), max(), cmp(), list().
A dictionary is like a list but instead of looking up an index to access values, you’ll be
using a unique key, which can be a number, string, or tuple.
Like lists dictionary can be updated new values can be added and existing values can
be updated.
Dictionary values can be removed using remove and del method.
Del method can be use to remove the entire dictionary and single value can c=be
removed by del method itself.
Like list and tuples dictionary have may function like len(), cmp(),str() and type().
Sorting is any process of arranging items systematically
Q.1 What is the output of print list[2:] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
B - abcd
C - [786, 2.23]
Answer : D
Explanation
It will print elements starting from 3rd element. Output would be [2.23, 'john', 70.2].
B - ['Hi!'] * 4
C - Error
Answer : A
Explanation
A - max(dict)
B - min(dict)
C - len(dict)
Answer : C
Explanation
len(dict) − Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.
a) list1 = list()
b) list1 = [].
c) list1 = list([1, 2, 3])
d) all of the mentioned
Answer: d
Explanation: Execute in the shell to verify
Answer: b
Explanation: Tuples are represented with round brackets.
>>>t=(1,2,4,3)
>>>t[1:3]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
Answer: c
Explanation: Slicing in tuples takes place just as it does in strings.
>>>t = (1, 2, 4, 3, 8, 9)
d = {"john":40, "peter":45}
d["john"]
a) 40
b) 45
c) “john”
d) “peter”
Answer: a
Explanation: Execute in the shell to verify.
>>>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].
Answer: a
Explanation: * operator concatenates tuple.
Q.15 Read the code shown below carefully and pick out the keys?
d = {"john":40, "peter":45}
d = {"john":40, "peter":45}
"john" in d
a) True
b) False
c) None
d) Error
Answer: a
Explanation: In can be used to check if the key is int dictionary.
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 == d2
a) True
b) False
c) None
d) Error
Answer:b
Q.18 What will be the output?
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 > d2
a) True
b) False
c) Error
d) None
Answer: c
Explanation: Arithmetic > operator cannot be used with dictionaries.
d = {"john":40, "peter":45}
d["john"]
a) 40
b) 45
c) “john”
d) “peter”
Answer: a
Explanation: Execute in the shell to verify.
Practice Questions
Q.4 What are the key differences of list, tuple, and dictionary?
Q.5 Is it possible to change the values of tuple and list ? Give explanation with example.
Q.7 What is sorting algorithm? What is the difference between bubble sort and insertion sort.
Laboratory Questions
Q.2 Write a program to find the compare two list are equal or not.
Q.3 Write a program to find generates a reverse list with and without built-in functions.
Q.4 Write a program to find the frequency of the elements of the list.
Q.5 Write a program to find sum and product of all the list elements.
Q.6 Write a program to find smallest number in the list without using min function.
Q.7 Write a program to find largest number in the list without using max function.
Q.9 Write a program to generate and print a dictionary that contains a number (between 1
and n) in the form (x, x*x). Sample Dictionary (n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4:
16, 5: 25}
Q.10 Write a program to convert a tuple to a string.