Unit III- PYTHON DATA STRUCTURES
LISTS
List is a versatile data type available in Python. It is a sequence in which elements are written
as a list of comma-separated values (items) between square brackets. The key feature of a list
is that it can have elements that belong to different data types.
Syntax:
List_variable = [val1, val2,...]
Example:
L=[10,20,30,40]
Accessing List Elements
We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a
list having 5 elements will have an index from 0 to 4.
Trying to access indexes other than these will raise an IndexError. The index must be an
integer. We can't use float or other types, this will result in TypeError.
Nested lists are accessed using nested indexing.
Example
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list[0])
print(my_list[2])
print(my_list[4])
n_list = ["Happy", [2, 0, 1, 5]]
print(n_list[0][1])
print(n_list[1][3])
print(my_list[4.0])
Output
p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float
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.
Figure: Indexing in List
Iterating Through a List
Using a for loop we can iterate through each item in a list.
for fruit in ['apple','banana','mango']:
print("I like",fruit)
Basic List Operations
Following table give the operations performed on lists:
Operation Description Example Output
len Returns length of the list len([1,2,3,4,5]) 5
+ Joins two list [1,2,3,4,5] + [10,11]
[1,2,3,4,5,10,1
1]
* Repeats elements in the list “Hello”,”world”*2
[‘Hello’,’world’,
‘Hello’,’world’]
in
Checks if the value is present
in the list
‘a’ in
[‘a’,’e’,’i’,’o’,’u
’]
True
not in
Checks if the value is not
present in the list
3 not in [1,2,4,5,6] True
max
Returns maximum value
in the list
N=[1,4,6,8,10,5]
print(max(N)) 10
min
Returns the minimum
value in the list
N=[1,4,6,8,10,5]
print(min(N)) 1
sum Adds the values in the list
N=[1,4,6,8,10,5]
print(sum(N)) 34
all
Returns true if all the
elements in the list are
true
N=[1,0,6,8,10,5]
print(all(N)) False
any
Returns true if any
element in the list is true
N=[1,0,6,8,10,5]
print(any(N)) True
list
Converts tuple, string, set
or dictionary into a list
L=list(“Hello”)
print(L)
[‘H’,’e’,’l’,’l’,’
o’]
sorted Returns a new sorted list
N=[1,0,6,8,10,5]
print(sorted(N))
[0,1,5,6,8,10]
Table: Basic List Operations
List Slicing:
Similar to strings, lists can also be sliced and concatenated. To access values in lists, square
brackets are used to slice along with the index or indices to get value stored at that index.
Syntax:
seq = ListName[start:stop:step] #accesses from start to stop-1
Example:
A=[1,2,3,4,5,6,7,8,9,10]
print(A) # prints [1,2,3,4,5,6,7,8,9,10]
print(A[2:5]) # prints [3,4,5]
print(A[ :5 ] #prints [1,2,3,4]
Print(A[ 3: ] #prints[4,5,6,7,8,9,10]
Print(A[ : ] #prints [1,2,3,4,5,6,7,8,9,10]
print(A[::2]) # prints [1,3,5,7,9]
print(A[1::3]) # prints [2,5,8]
List Mutability:
The list is a mutable data structure. This means that its elements can be replaced, inserted and
removed. A slice operator on the left side of an assignment operation can update single or
multiple elements of a list. New elements can be added to the list using append() method.
The following code replaces ‘Ram’ which is at index 0 in the stulist by ‘Priya’. The values
are shown in the output for both instances.
Example:
l = [10,15,30,45]
print l # prints [10,15,30,45]
l[1] = 100
print l # prints [10,100,30,45]
List aliasing:
When one list is assigned to another list using the assignment operator (=), then a new copy
of the list is not made. Instead, assignment makes two variables point to the one list in
memory.
Example:
list1= [1,2,3,4,5]
list2= list1
print(list2) #prints [1,2,3,4,5]
list2[2]=200
print (list1) # prints[1,2,200,4,5]
Cloning Lists:
If you want to modify a list and also keep a copy of the original list, then you should create a
separate copy of the list (not just the reference). This process is called cloning. The slice
operation is used to clone a list.
Example:
l1=[1,2,3,4,5,6,7,8,9,10]
l2=l1.copy()
print(l2) # prints [1,2,3,4,5,6,7,8,9,10]
l3=l1[ :5]
print(l3) #prints[1,2,3,4]
List Methods:
Operation Description Syntax Example Output
append()
Appends an element
at the last
to the list.
list.append(val)
L=[10,20,30,40]
L.append(100)
print(L1)
[10,20,30,40,100]
count() Counts the number list.count(val) L=[10,20,30,20] 2
of times an element
appears in the list.
print(L.count(20
))
index()
Returns the lowest
index of an element
in the list.
list.index(val)
L=[10,20,30,20]
print(L.index(20
))
1
insert()
Inserts the value at
the specified index
in the list
list.insert(index,
val)
L=[10,20,30,20]
L.insert(1,100)
print(L)
[10,100,20,30,20]
pop()
Removes the
element at the
specified index from
the list
list.pop(index)
L=[10,20,30,20]
L.insert(1)
print(L)
[10,30,20]
remove()
Removes or deletes
val from the list
list.remove(val)
L=[10,20,30,20]
L.remove(10)
print(L)
[20,30,20]
reverse()
Reverse the
elements in the list.
list.reverse()
L=[10,20,30,20]
L.reverse()
print(L)
[20,30,20,10]
sort()
Sorts the elements
in the list.
list.sort()
L=[10,20,30,20]
L.sort()
print(L)
[10,20,20,30]
extend()
Adds the elements
in a list to the end of
another list
list.extend(list2)
L=[10,20,30]
L1=[100,2000]
L.extend(L1)
print(L)
[10,20,30,100,200
]
copy()
Used to copy the
content of list from
one to another
list1=list.copy()
L=[10,20,30,20]
L1=L.copy()
print(L1)
[10,20,30,20]
len()
Finds the length of
the list
len(list)
L=[10,20,30,20]
print(len(L))
4
max()
Gives the maximum
element in the list
max(list)
L=[10,20,30,20]
print(max(L))
30
min() Gives the minimum
element in the list
min(list)
L=[10,20,30,20]
10
print(min(L))
clear()
Clears all the
element in the list
list.clear()
L=[10,20,30,20]
L.clear()
print(L)
[]
del deletes the entire list del list
L=[10,20,30,20]
del L
Name Error
Table: List Functions in Python
Python's for and in constructs are extremely useful especially when working with lists. The
forvar in list statement is an easy way to access each element in a list (or any other sequence).
For example, in the following code, the for loop is used to access each item in the list.
Python program to print sum of elements in a List
list1=[3,5,7,6,2,9]
sum=0
for i in list1:
sum +=i
print sum
Output:
32
Python program to print odd Numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93]
# iterating each number in list
for num in list1:
# checking condition
if num % 2 != 0:
print(num, end = " ")
Output:
21
45
93
Program to find sum of odd and even numbers in a list
NumList=[] #empty list
evenSum=0 #declare and initialised variable evenSum to sum of even numbers
oddSum=0 #declare and initialised variable oddSum to sum of odd numbers
Number=int(input("Please enter the total number of list elements: "))
for i in range( Number):
value=input("Please enter the value: ")
NumList.append(value)
for j in range(Number):
if(NumList[j]%2==0):
evenSum=evenSum+NumList[j]
else:
oddSum=oddSum+NumList[j]
print("The sum of even numbers in the list= ",evenSum)
print("The sum of odd numbers in the list= ",oddSum)
Output:
Please enter the total number of list elements: 6
Please enter the value: 12
Please enter the value: 21
Please enter the value: 23
Please enter the value: 32
Please enter the value: 34
Please enter the value: 43
The sum of even numbers in the list= 78
The sum of odd numbers in the list= 87
Python program to count the number of strings where the string length is 2 or more and
the first and last character are same from a given list of strings.
words = ['abc', 'xyz', 'aba', '1221']
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
print(“Result “,ctr)
python program that takes a list and returns a new list that contains all the elements of
the first list without any duplicates.
# all the elements of the first list minus duplicates.
inpt_lst = [1,2,3,4,3,2,1]
reslt_lst = []
for i in inpt_lst:
if i not in reslt_lst:
reslt_lst.append(i)
print(“Result “, reslt_lst)
Output
Result [1,2,3,4]
NESTED LISTS
A list can contain any sort object, even another list (sublist), which in turn can contain
sublists themselves, and so on. This is known as nested list.
Example
L = ['A', ['BB', ['CCC', 'DDD'], 'EE', 'FF'], 'G', 'H']
Figure: Nested List
LIST COMPREHENSIONS
Python also supports computed lists called list comprehensions having the following syntax.
List = [expression for variable in sequence]
where, the expression is evaluated once, for every item in the sequence.
List comprehensions help programmers to create lists in a concise way. This is mainly
beneficial to make new lists where each element is the obtained by applying some operations
to each member of another sequence or iterable. List comprehension is also used to
create a subsequence of those elements that satisfy a certain condition.
Example
c= [i**3 for i in range(11)]
print (c)
Output:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Example
print( [(x,y) for x in [10,20,30] for y in [30,10,40] if x! = y] )
Output:[(10, 30), (10, 40), (20, 30), (20, 10), (20, 40), (30, 10), (30, 40)]
TUPLES
Like lists, tuple is another data structure supported by Python. It is very similar to lists but
differs in two things.
 First, a tuple is a sequence of immutable objects. This means that while you can
change the value of one or more items in a list, you cannot change the values in a
tuple.
 Second, tuples use parentheses to define its elements whereas lists use square
brackets.
Creating Tuple
Creating a tuple is very simple and almost similar to creating a list. For creating a tuple,
generally you need to just put the different comma-separated values within a parenthesis as
shown below.
Tuple_name = (val1, val2,...)
whereval (or values) can be an integer, a floating number, a character, or a string.
Example
tuple1= (‘abcd’, 345 , 3.2, ‘python’, 3.14)
print(tuple1)
Output:
(‘abcd’, 345, 3.2,’python’, 3.14)
Accessing Values in a Tuple:
Like other sequences (strings and lists) covered so far, indices in a tuple also starts at 0. You
can even perform operations like slice, concatenate, etc. on a tuple. For example, to access
values in tuple, slice operation is used along with the index or indices to obtain value stored
at that index.
Example
T = (1,2,3,4,5,6,7,8,9,10)
print(“Tuple[ 3:6] =”,T[3:6])
print(“Tuple[ : 4] =”, T[ :4])
print(“Tuple[ 4 : ] =”, T[ 4 : ])
print(“Tuple[ : ] =”, T[ : ])
Output:
Tuple[ 3:6] = (4,5,6)
Tuple[ : 4] = (1,2,3,4)
Tuple[ 4 : ] = (5,6,7,8,9,10)
Tuple[ : ] = (1,2,3,4,5,6,7,8,9,10)
Deleting Elements in Tuple:
Since tuple is an immutable data structure, you cannot delete value(s) from it. Of course, we
can create a new tuple that has all elements in our tuple except the ones we don't want (those
we wanted to be deleted).
tup1 = ('C', 'C++', 'python',
1997, 2000)
tup1[0]=’Java’
Output:
Traceback (most recent call
last):
File "main.py", line 2, in
tup1[0]='Java'
TypeError: 'tuple' object does
not support item assignment
Tup1 = (1,2,3,4,5 )
del(Tup1[3])
print(Tup1)
Output:
Traceback (most recent call
last):
File "main.py", line 2, in
del(Tup1[3])
TypeError: 'tuple' object does
not support item deletion
Tup1 = (1,2,3,4,5 )
del(Tup1)
print(Tup1)
Output:
Traceback (most recent call
last):
File "main.py", line 3, in
print(Tup1)
NameError : name ‘Tup1’ is
notdefined
Basic Tuple Operations:
Operation Expression Output
Len len(1,2,3,4,5) 5
concatenation (1,2,3) + (4,5,6) (1,2,3,4,5,6)
Repetition (‘Good’) *3 (‘GoodGoodGood’)
In 5 in (1,2,3,4,5,6,7) True
not in 5 not in (1,2,3,4,5,6,7) False
max max(2,4,6,8,13,7) 13
min min(2,4,6,8,13,7) 2
Iteration for i in (1,2,3,4,5,6)
print(i) 1,2,3,4,5,6
Comparison
T1=(1,2,3,4,5)
T2=(1,2,3,4,5)
print(T1 >T2)
False
tuple Tuple(“Hello”)
Tuple([1,2,3,4,5])
(‘H’,’e’,’l’,’l’,’o’)
(1,2,3,4,5)
Tuple Assignment:
Tuple assignment is a very powerful feature in Python. It allows a tuple of variables on the
left side of the assignment operator to be assigned values from a tuple given on the right side
of the assignment operator. Each value is assigned to its respective variable. In case, an
expression is specified on the right side of the assignment operator, first that expression is
evaluated and then assignment is done.
Example:
a,b,c) = (1,2,3)
print(a,b,c)
Tup1=(100,200,300)
(t1,t2,t3)= Tup1
print (t1,t2,t3)
(a,b,c) = (2+5, 5/3+4, 9%6)
print(a,b,c)
(t1,t2,t3)=(1,2)
print (t1,t2,t3)
Output:
1 2 3
100 200 300
7 5.666667 3
Traceback (most recent call last) :
File “<stdin>”, line 8 in (t1,t2,t3)=(1,2)
ValueError : need more than 2 values to unpack
Differences between lists and tuples:
 Lists are enclosed in square brackets [ ] and their elements and size can be
changed.
 But, tuples are enclosed in parentheses () and cannot be updated.
 Tuples are immutable, so iterating through tuple is faster than with list.
 Tuples can be thought of as read-only lists.
Advantages of Tuple over List:
 Tuples are used to store values of different data types. Lists can however,
store data of similar data types.
 Since tuples are immutable, iterating through tuples is faster than
iterating over a list. This means that a tuple performs better than a list.
 Tuples can be used as key for a dictionary but lists cannot be used as keys.
 Tuples are best suited for storing data that is write-protected.
 Tuples can be used in place of lists where the number of values is known and
small.
 If you are passing a tuple as an argument to a function, then the potential
for unexpected behaviour due to aliasing gets reduced.
 Multiple values from a function can be returned using a tuple.
 Tuples are used to format strings.
SETS
A set is an unordered collection of items. Every set element is unique (no duplicates) and
must be immutable (cannot be changed).However, a set itself is mutable. We can add or
remove items from it. Sets can also be used to perform mathematical set operations like
union, intersection, symmetric difference, etc.
Creating Python Sets
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma, or by using the built-in set() function.
It can have any number of items and they may be of different types (integer, float, tuple,
string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its
elements.
Example
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
Output:
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
Modifying a set:
Sets are mutable. However, since they are unordered, indexing has no meaning. We cannot
access or change an element of a set using indexing or slicing. Set data type does not support
it. We can add a single element using the add () method, and multiple elements using the
update() method. The update () method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
Example
y_set = {1, 3}
print(my_set)
# add an element
my_set.add(2)
print(my_set)
# add multiple elements
my_set.update([2, 3, 4])
print(my_set)
my_set.update([4, 5], {1, 6, 8})
print(my_set)
Output:
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
Removing elements from a set:
A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set unchanged if
the element is not present in the set. On the other hand, the remove() function will raise an
error in such a condition (if element is not present in the set).
Example
my_set = {1, 3, 4, 5, 6}
print(my_set)
my_set.discard(4)
print(my_set)
# remove an element
my_set.remove(6)
print(my_set)
# discard an element
my_set.discard(2)
print(my_set)
Output:
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Python Set Operations
Set Union:
Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished using the union() method.
Example:
# Set union method
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B)
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection:
Intersection of A and B is a set of elements that are common in both the sets. Intersection is
performed using & operator. Same can be accomplished using the intersection() method.
Example:
# Intersection of sets
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A & B)
Output:
{4, 5}
Set Difference:
Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of elements in B but not in A. Difference is performed using -
operator. Same can be accomplished using the difference() method.
Example:
# Difference of two sets
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A - B)
Output:
{1, 2, 3}
Set Symmetric Difference:
Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding
the intersection).Symmetric difference is performed using ^ operator. Same can be
accomplished using the method symmetric_difference().
Example:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A ^ B)
Output:
{1, 2, 3, 6, 7, 8}
Set Methods
Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new
set
difference_update() Removes all elements of another set from this set
discard() Removes an element from the set if it is a member.
(Do nothing if the element is not in set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and
another
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
pop() Removes and returns an arbitrary set element.
Raises KeyError if the set is empty
remove() Removes an element from the set. If the element is
not a member, raises a KeyError
symmetric_difference() Returns the symmetric difference of two sets as a
new set
symmetric_difference_update() Updates a set with the symmetric difference of
itself and another
union() Returns the union of sets in a new set
update() Updates the set with the union of itself and others
Table: Methods used with Sets
DICTIONARIES
Dictionary is a data structure in which we store values as a pair of key and value. Each key is
separated from its value by a colon (:), and consecutive items are separated by commas. The
entire items in a dictionary are enclosed in curly brackets({}).
The syntax for defining a dictionary is
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ….}
Example:
Dict = { ‘RollNo’ : ‘16/001’ , ‘Name’ : ‘Arav’ , ‘Course’ : ‘Btech’}
print(Dict)
Output:
{ ‘RollNo’ : ‘16/001’ , ‘Name’ : ‘Arav’ , ‘Course’ : ‘Btech’}
Accessing Elements from Dictionary:
While indexing is used with other data types to access values, a dictionary uses keys. Keys
can be used either inside square brackets [] or with the get() method. 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.
Example:
my_dict = {'name': 'Jack', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
print(my_dict.get('address'))
print(my_dict['address'])
Output:
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
Changing and Adding Dictionary elements:
Dictionaries are mutable. We can add new items or change the value of existing items using
an assignment operator. If the key is already present, then the existing value gets updated. In
case the key is not present, a new (key: value) pair is added to the dictionary.
Example:
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
Output:
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}
Removing elements from Dictionary:
We can remove a particular item in a dictionary by using the pop() method. This method
removes an item with the provided key and returns the value. The popitem() method can be
used to remove and return an arbitrary (key, value) item pair from the dictionary. All the
items can be removed at once, using the clear() method. We can also use the del keyword to
remove individual items or the entire dictionary itself.
Example:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
print(squares.pop(4))
print(squares)
# remove an arbitrary item, return (key,value)
print(squares.popitem())
print(squares)
# remove all items
squares.clear()
print(squares)
# delete the dictionary itself
del squares
Output:
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
Dictionary Methods
Method Description
clear()
Removes all items from the dictionary.
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear()
print(my_dict) # Output: {}
copy()
Returns a shallow copy of the dictionary.
original_dict = {'a': 1, 'b': 2, 'c': 3}
copied_dict = original_dict.copy()
print(copied_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
fromkeys(seq[, v])
Returns a new dictionary with keys from seq and value equal to v
(defaults to None).
keys = ['a', 'b', 'c']
new_dict = dict.fromkeys(keys, 0)
print(new_dict) # Output: {'a': 0, 'b': 0, 'c': 0}
get(key[,d])
Returns the value of the key. If the key does not exist, returns d
(defaults to None).
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.get('a')) # Output: 1
print(my_dict.get('d', 'Key not found')) # Output: Key not found
items() Return a new object of the dictionary's items in (key, value)
format.
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.items())
Output: dict_items([('a', 1), ('b', 2), ('c', 3)])
keys()
Returns a new object of the dictionary's keys.
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.keys())
Output: dict_keys(['a', 'b', 'c'])
pop(key[,d])
Removes the item with the key and returns its value or d if key is
not found. If d is not provided and the key is not found, it raises
KeyError.
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.pop('b')) # Output: 2
print(my_dict) # Output: {'a': 1, 'c': 3}
popitem()
Removes and returns an arbitrary item (key, value). Raises
KeyError if the dictionary is empty.
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.popitem()) # Output: ('c', 3)
print(my_dict) # Output: {'a': 1, 'b': 2}
setdefault(key[,d])
Returns the corresponding value if the key is in the dictionary. If
not, inserts the key with a value of d and returns d (defaults to
None).
my_dict = {'a': 1, 'b': 2}
value = my_dict.setdefault('c', 3)
print(value) # Output: 3
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
update([other]) Updates the dictionary with the key/value pairs from other,
overwriting existing keys.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}
# Example 2: Updating with key-value pairs
dict1 = {'a': 1, 'b': 2}
dict1.update(c=3, d=4)
print(dict1) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
values()
Returns a new object of the dictionary's values
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.values()) # Output: dict_values([1, 2, 3])
Table: Dictionary Method in Python
Python script to print a dictionary where the keys are numbers between 1 and 15 (both
included) and the values are square of keys
d=dict()
for x in range(1,16):
d[x]=x**2
print(d)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14:
196, 15: 225}
DICTIONARY COMPREHENSION
Dictionary comprehension is an elegant and concise way to create dictionaries.
Syntax
dictionary = {key: value for vars in iterable}
Example
square_dict = {num: num*num for num in range(1, 11)}
print(square_dict)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

Python Materials- Lists, Dictionary, Tuple

  • 1.
    Unit III- PYTHONDATA STRUCTURES LISTS List is a versatile data type available in Python. It is a sequence in which elements are written as a list of comma-separated values (items) between square brackets. The key feature of a list is that it can have elements that belong to different data types. Syntax: List_variable = [val1, val2,...] Example: L=[10,20,30,40] Accessing List Elements We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4. Trying to access indexes other than these will raise an IndexError. The index must be an integer. We can't use float or other types, this will result in TypeError. Nested lists are accessed using nested indexing. Example my_list = ['p', 'r', 'o', 'b', 'e'] print(my_list[0]) print(my_list[2]) print(my_list[4]) n_list = ["Happy", [2, 0, 1, 5]] print(n_list[0][1]) print(n_list[1][3]) print(my_list[4.0])
  • 2.
    Output p o e a 5 Traceback (most recentcall last): File "<string>", line 21, in <module> TypeError: list indices must be integers or slices, not float 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. Figure: Indexing in List Iterating Through a List Using a for loop we can iterate through each item in a list. for fruit in ['apple','banana','mango']: print("I like",fruit) Basic List Operations
  • 3.
    Following table givethe operations performed on lists: Operation Description Example Output len Returns length of the list len([1,2,3,4,5]) 5 + Joins two list [1,2,3,4,5] + [10,11] [1,2,3,4,5,10,1 1] * Repeats elements in the list “Hello”,”world”*2 [‘Hello’,’world’, ‘Hello’,’world’] in Checks if the value is present in the list ‘a’ in [‘a’,’e’,’i’,’o’,’u ’] True not in Checks if the value is not present in the list 3 not in [1,2,4,5,6] True max Returns maximum value in the list N=[1,4,6,8,10,5] print(max(N)) 10 min Returns the minimum value in the list N=[1,4,6,8,10,5] print(min(N)) 1 sum Adds the values in the list N=[1,4,6,8,10,5] print(sum(N)) 34 all Returns true if all the elements in the list are true N=[1,0,6,8,10,5] print(all(N)) False any Returns true if any element in the list is true N=[1,0,6,8,10,5] print(any(N)) True list Converts tuple, string, set or dictionary into a list L=list(“Hello”) print(L) [‘H’,’e’,’l’,’l’,’ o’] sorted Returns a new sorted list N=[1,0,6,8,10,5] print(sorted(N)) [0,1,5,6,8,10] Table: Basic List Operations
  • 4.
    List Slicing: Similar tostrings, lists can also be sliced and concatenated. To access values in lists, square brackets are used to slice along with the index or indices to get value stored at that index. Syntax: seq = ListName[start:stop:step] #accesses from start to stop-1 Example: A=[1,2,3,4,5,6,7,8,9,10] print(A) # prints [1,2,3,4,5,6,7,8,9,10] print(A[2:5]) # prints [3,4,5] print(A[ :5 ] #prints [1,2,3,4] Print(A[ 3: ] #prints[4,5,6,7,8,9,10] Print(A[ : ] #prints [1,2,3,4,5,6,7,8,9,10] print(A[::2]) # prints [1,3,5,7,9] print(A[1::3]) # prints [2,5,8] List Mutability: The list is a mutable data structure. This means that its elements can be replaced, inserted and removed. A slice operator on the left side of an assignment operation can update single or multiple elements of a list. New elements can be added to the list using append() method. The following code replaces ‘Ram’ which is at index 0 in the stulist by ‘Priya’. The values are shown in the output for both instances. Example: l = [10,15,30,45] print l # prints [10,15,30,45] l[1] = 100 print l # prints [10,100,30,45]
  • 5.
    List aliasing: When onelist is assigned to another list using the assignment operator (=), then a new copy of the list is not made. Instead, assignment makes two variables point to the one list in memory. Example: list1= [1,2,3,4,5] list2= list1 print(list2) #prints [1,2,3,4,5] list2[2]=200 print (list1) # prints[1,2,200,4,5] Cloning Lists: If you want to modify a list and also keep a copy of the original list, then you should create a separate copy of the list (not just the reference). This process is called cloning. The slice operation is used to clone a list. Example: l1=[1,2,3,4,5,6,7,8,9,10] l2=l1.copy() print(l2) # prints [1,2,3,4,5,6,7,8,9,10] l3=l1[ :5] print(l3) #prints[1,2,3,4] List Methods: Operation Description Syntax Example Output append() Appends an element at the last to the list. list.append(val) L=[10,20,30,40] L.append(100) print(L1) [10,20,30,40,100] count() Counts the number list.count(val) L=[10,20,30,20] 2
  • 6.
    of times anelement appears in the list. print(L.count(20 )) index() Returns the lowest index of an element in the list. list.index(val) L=[10,20,30,20] print(L.index(20 )) 1 insert() Inserts the value at the specified index in the list list.insert(index, val) L=[10,20,30,20] L.insert(1,100) print(L) [10,100,20,30,20] pop() Removes the element at the specified index from the list list.pop(index) L=[10,20,30,20] L.insert(1) print(L) [10,30,20] remove() Removes or deletes val from the list list.remove(val) L=[10,20,30,20] L.remove(10) print(L) [20,30,20] reverse() Reverse the elements in the list. list.reverse() L=[10,20,30,20] L.reverse() print(L) [20,30,20,10] sort() Sorts the elements in the list. list.sort() L=[10,20,30,20] L.sort() print(L) [10,20,20,30] extend() Adds the elements in a list to the end of another list list.extend(list2) L=[10,20,30] L1=[100,2000] L.extend(L1) print(L) [10,20,30,100,200 ] copy() Used to copy the content of list from one to another list1=list.copy() L=[10,20,30,20] L1=L.copy() print(L1) [10,20,30,20] len() Finds the length of the list len(list) L=[10,20,30,20] print(len(L)) 4 max() Gives the maximum element in the list max(list) L=[10,20,30,20] print(max(L)) 30 min() Gives the minimum element in the list min(list) L=[10,20,30,20] 10
  • 7.
    print(min(L)) clear() Clears all the elementin the list list.clear() L=[10,20,30,20] L.clear() print(L) [] del deletes the entire list del list L=[10,20,30,20] del L Name Error Table: List Functions in Python Python's for and in constructs are extremely useful especially when working with lists. The forvar in list statement is an easy way to access each element in a list (or any other sequence). For example, in the following code, the for loop is used to access each item in the list. Python program to print sum of elements in a List list1=[3,5,7,6,2,9] sum=0 for i in list1: sum +=i print sum Output: 32 Python program to print odd Numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93] # iterating each number in list for num in list1: # checking condition if num % 2 != 0: print(num, end = " ") Output:
  • 8.
    21 45 93 Program to findsum of odd and even numbers in a list NumList=[] #empty list evenSum=0 #declare and initialised variable evenSum to sum of even numbers oddSum=0 #declare and initialised variable oddSum to sum of odd numbers Number=int(input("Please enter the total number of list elements: ")) for i in range( Number): value=input("Please enter the value: ") NumList.append(value) for j in range(Number): if(NumList[j]%2==0): evenSum=evenSum+NumList[j] else: oddSum=oddSum+NumList[j] print("The sum of even numbers in the list= ",evenSum) print("The sum of odd numbers in the list= ",oddSum) Output: Please enter the total number of list elements: 6 Please enter the value: 12 Please enter the value: 21 Please enter the value: 23 Please enter the value: 32 Please enter the value: 34 Please enter the value: 43 The sum of even numbers in the list= 78 The sum of odd numbers in the list= 87 Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. words = ['abc', 'xyz', 'aba', '1221']
  • 9.
    ctr = 0 forword in words: if len(word) > 1 and word[0] == word[-1]: ctr += 1 print(“Result “,ctr) python program that takes a list and returns a new list that contains all the elements of the first list without any duplicates. # all the elements of the first list minus duplicates. inpt_lst = [1,2,3,4,3,2,1] reslt_lst = [] for i in inpt_lst: if i not in reslt_lst: reslt_lst.append(i) print(“Result “, reslt_lst) Output Result [1,2,3,4] NESTED LISTS A list can contain any sort object, even another list (sublist), which in turn can contain sublists themselves, and so on. This is known as nested list. Example L = ['A', ['BB', ['CCC', 'DDD'], 'EE', 'FF'], 'G', 'H']
  • 10.
    Figure: Nested List LISTCOMPREHENSIONS Python also supports computed lists called list comprehensions having the following syntax. List = [expression for variable in sequence] where, the expression is evaluated once, for every item in the sequence. List comprehensions help programmers to create lists in a concise way. This is mainly beneficial to make new lists where each element is the obtained by applying some operations to each member of another sequence or iterable. List comprehension is also used to create a subsequence of those elements that satisfy a certain condition. Example c= [i**3 for i in range(11)] print (c) Output: [0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] Example print( [(x,y) for x in [10,20,30] for y in [30,10,40] if x! = y] ) Output:[(10, 30), (10, 40), (20, 30), (20, 10), (20, 40), (30, 10), (30, 40)]
  • 11.
    TUPLES Like lists, tupleis another data structure supported by Python. It is very similar to lists but differs in two things.  First, a tuple is a sequence of immutable objects. This means that while you can change the value of one or more items in a list, you cannot change the values in a tuple.  Second, tuples use parentheses to define its elements whereas lists use square brackets. Creating Tuple Creating a tuple is very simple and almost similar to creating a list. For creating a tuple, generally you need to just put the different comma-separated values within a parenthesis as shown below. Tuple_name = (val1, val2,...) whereval (or values) can be an integer, a floating number, a character, or a string. Example tuple1= (‘abcd’, 345 , 3.2, ‘python’, 3.14) print(tuple1) Output: (‘abcd’, 345, 3.2,’python’, 3.14) Accessing Values in a Tuple: Like other sequences (strings and lists) covered so far, indices in a tuple also starts at 0. You can even perform operations like slice, concatenate, etc. on a tuple. For example, to access values in tuple, slice operation is used along with the index or indices to obtain value stored at that index. Example T = (1,2,3,4,5,6,7,8,9,10) print(“Tuple[ 3:6] =”,T[3:6]) print(“Tuple[ : 4] =”, T[ :4]) print(“Tuple[ 4 : ] =”, T[ 4 : ]) print(“Tuple[ : ] =”, T[ : ])
  • 12.
    Output: Tuple[ 3:6] =(4,5,6) Tuple[ : 4] = (1,2,3,4) Tuple[ 4 : ] = (5,6,7,8,9,10) Tuple[ : ] = (1,2,3,4,5,6,7,8,9,10) Deleting Elements in Tuple: Since tuple is an immutable data structure, you cannot delete value(s) from it. Of course, we can create a new tuple that has all elements in our tuple except the ones we don't want (those we wanted to be deleted). tup1 = ('C', 'C++', 'python', 1997, 2000) tup1[0]=’Java’ Output: Traceback (most recent call last): File "main.py", line 2, in tup1[0]='Java' TypeError: 'tuple' object does not support item assignment Tup1 = (1,2,3,4,5 ) del(Tup1[3]) print(Tup1) Output: Traceback (most recent call last): File "main.py", line 2, in del(Tup1[3]) TypeError: 'tuple' object does not support item deletion Tup1 = (1,2,3,4,5 ) del(Tup1) print(Tup1) Output: Traceback (most recent call last): File "main.py", line 3, in print(Tup1) NameError : name ‘Tup1’ is notdefined Basic Tuple Operations: Operation Expression Output Len len(1,2,3,4,5) 5 concatenation (1,2,3) + (4,5,6) (1,2,3,4,5,6) Repetition (‘Good’) *3 (‘GoodGoodGood’) In 5 in (1,2,3,4,5,6,7) True not in 5 not in (1,2,3,4,5,6,7) False max max(2,4,6,8,13,7) 13
  • 13.
    min min(2,4,6,8,13,7) 2 Iterationfor i in (1,2,3,4,5,6) print(i) 1,2,3,4,5,6 Comparison T1=(1,2,3,4,5) T2=(1,2,3,4,5) print(T1 >T2) False tuple Tuple(“Hello”) Tuple([1,2,3,4,5]) (‘H’,’e’,’l’,’l’,’o’) (1,2,3,4,5) Tuple Assignment: Tuple assignment is a very powerful feature in Python. It allows a tuple of variables on the left side of the assignment operator to be assigned values from a tuple given on the right side of the assignment operator. Each value is assigned to its respective variable. In case, an expression is specified on the right side of the assignment operator, first that expression is evaluated and then assignment is done. Example: a,b,c) = (1,2,3) print(a,b,c) Tup1=(100,200,300) (t1,t2,t3)= Tup1 print (t1,t2,t3) (a,b,c) = (2+5, 5/3+4, 9%6) print(a,b,c) (t1,t2,t3)=(1,2) print (t1,t2,t3) Output: 1 2 3 100 200 300 7 5.666667 3 Traceback (most recent call last) : File “<stdin>”, line 8 in (t1,t2,t3)=(1,2) ValueError : need more than 2 values to unpack
  • 14.
    Differences between listsand tuples:  Lists are enclosed in square brackets [ ] and their elements and size can be changed.  But, tuples are enclosed in parentheses () and cannot be updated.  Tuples are immutable, so iterating through tuple is faster than with list.  Tuples can be thought of as read-only lists. Advantages of Tuple over List:  Tuples are used to store values of different data types. Lists can however, store data of similar data types.  Since tuples are immutable, iterating through tuples is faster than iterating over a list. This means that a tuple performs better than a list.  Tuples can be used as key for a dictionary but lists cannot be used as keys.  Tuples are best suited for storing data that is write-protected.  Tuples can be used in place of lists where the number of values is known and small.  If you are passing a tuple as an argument to a function, then the potential for unexpected behaviour due to aliasing gets reduced.  Multiple values from a function can be returned using a tuple.  Tuples are used to format strings. SETS A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed).However, a set itself is mutable. We can add or remove items from it. Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc. Creating Python Sets A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function. It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements. Example
  • 15.
    my_set = {1,2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) Output: {1, 2, 3} {1.0, (1, 2, 3), 'Hello'} Modifying a set: Sets are mutable. However, since they are unordered, indexing has no meaning. We cannot access or change an element of a set using indexing or slicing. Set data type does not support it. We can add a single element using the add () method, and multiple elements using the update() method. The update () method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided. Example y_set = {1, 3} print(my_set) # add an element my_set.add(2) print(my_set) # add multiple elements my_set.update([2, 3, 4]) print(my_set) my_set.update([4, 5], {1, 6, 8}) print(my_set) Output: {1, 3} {1, 2, 3} {1, 2, 3, 4} {1, 2, 3, 4, 5, 6, 8} Removing elements from a set: A particular item can be removed from a set using the methods discard() and remove().
  • 16.
    The only differencebetween the two is that the discard() function leaves a set unchanged if the element is not present in the set. On the other hand, the remove() function will raise an error in such a condition (if element is not present in the set). Example my_set = {1, 3, 4, 5, 6} print(my_set) my_set.discard(4) print(my_set) # remove an element my_set.remove(6) print(my_set) # discard an element my_set.discard(2) print(my_set) Output: {1, 3, 4, 5, 6} {1, 3, 5, 6} {1, 3, 5} {1, 3, 5} Python Set Operations Set Union: Union of A and B is a set of all elements from both sets. Union is performed using | operator. Same can be accomplished using the union() method. Example: # Set union method A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A | B) Output: {1, 2, 3, 4, 5, 6, 7, 8} Set Intersection:
  • 17.
    Intersection of Aand B is a set of elements that are common in both the sets. Intersection is performed using & operator. Same can be accomplished using the intersection() method. Example: # Intersection of sets A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A & B) Output: {4, 5} Set Difference: Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of elements in B but not in A. Difference is performed using - operator. Same can be accomplished using the difference() method. Example: # Difference of two sets A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A - B) Output: {1, 2, 3} Set Symmetric Difference: Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding the intersection).Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric_difference(). Example: A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A ^ B) Output: {1, 2, 3, 6, 7, 8}
  • 18.
    Set Methods Method Description add()Adds an element to the set clear() Removes all elements from the set copy() Returns a copy of the set difference() Returns the difference of two or more sets as a new set difference_update() Removes all elements of another set from this set discard() Removes an element from the set if it is a member. (Do nothing if the element is not in set) intersection() Returns the intersection of two sets as a new set intersection_update() Updates the set with the intersection of itself and another isdisjoint() Returns True if two sets have a null intersection issubset() Returns True if another set contains this set issuperset() Returns True if this set contains another set pop() Removes and returns an arbitrary set element. Raises KeyError if the set is empty remove() Removes an element from the set. If the element is not a member, raises a KeyError symmetric_difference() Returns the symmetric difference of two sets as a new set symmetric_difference_update() Updates a set with the symmetric difference of itself and another union() Returns the union of sets in a new set update() Updates the set with the union of itself and others Table: Methods used with Sets
  • 19.
    DICTIONARIES Dictionary is adata structure in which we store values as a pair of key and value. Each key is separated from its value by a colon (:), and consecutive items are separated by commas. The entire items in a dictionary are enclosed in curly brackets({}). The syntax for defining a dictionary is dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ….} Example: Dict = { ‘RollNo’ : ‘16/001’ , ‘Name’ : ‘Arav’ , ‘Course’ : ‘Btech’} print(Dict) Output: { ‘RollNo’ : ‘16/001’ , ‘Name’ : ‘Arav’ , ‘Course’ : ‘Btech’} Accessing Elements from Dictionary: While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside square brackets [] or with the get() method. 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. Example: my_dict = {'name': 'Jack', 'age': 26} print(my_dict['name']) print(my_dict.get('age')) print(my_dict.get('address')) print(my_dict['address']) Output: Jack 26 None Traceback (most recent call last): File "<string>", line 15, in <module> print(my_dict['address'])
  • 20.
    KeyError: 'address' Changing andAdding Dictionary elements: Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator. If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value) pair is added to the dictionary. Example: # Changing and adding Dictionary Elements my_dict = {'name': 'Jack', 'age': 26} # update value my_dict['age'] = 27 print(my_dict) # add item my_dict['address'] = 'Downtown' print(my_dict) Output: {'name': 'Jack', 'age': 27} {'name': 'Jack', 'age': 27, 'address': 'Downtown'} Removing elements from Dictionary: We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value. The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All the items can be removed at once, using the clear() method. We can also use the del keyword to remove individual items or the entire dictionary itself. Example: squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # remove a particular item, returns its value print(squares.pop(4)) print(squares) # remove an arbitrary item, return (key,value) print(squares.popitem()) print(squares) # remove all items
  • 21.
    squares.clear() print(squares) # delete thedictionary itself del squares Output: 16 {1: 1, 2: 4, 3: 9, 5: 25} (5, 25) {1: 1, 2: 4, 3: 9} {} Dictionary Methods Method Description clear() Removes all items from the dictionary. my_dict = {'a': 1, 'b': 2, 'c': 3} my_dict.clear() print(my_dict) # Output: {} copy() Returns a shallow copy of the dictionary. original_dict = {'a': 1, 'b': 2, 'c': 3} copied_dict = original_dict.copy() print(copied_dict) # Output: {'a': 1, 'b': 2, 'c': 3} fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None). keys = ['a', 'b', 'c'] new_dict = dict.fromkeys(keys, 0) print(new_dict) # Output: {'a': 0, 'b': 0, 'c': 0} get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None). my_dict = {'a': 1, 'b': 2, 'c': 3} print(my_dict.get('a')) # Output: 1 print(my_dict.get('d', 'Key not found')) # Output: Key not found items() Return a new object of the dictionary's items in (key, value) format. my_dict = {'a': 1, 'b': 2, 'c': 3}
  • 22.
    print(my_dict.items()) Output: dict_items([('a', 1),('b', 2), ('c', 3)]) keys() Returns a new object of the dictionary's keys. my_dict = {'a': 1, 'b': 2, 'c': 3} print(my_dict.keys()) Output: dict_keys(['a', 'b', 'c']) pop(key[,d]) Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError. my_dict = {'a': 1, 'b': 2, 'c': 3} print(my_dict.pop('b')) # Output: 2 print(my_dict) # Output: {'a': 1, 'c': 3} popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty. my_dict = {'a': 1, 'b': 2, 'c': 3} print(my_dict.popitem()) # Output: ('c', 3) print(my_dict) # Output: {'a': 1, 'b': 2} setdefault(key[,d]) Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None). my_dict = {'a': 1, 'b': 2} value = my_dict.setdefault('c', 3) print(value) # Output: 3 print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3} update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys. dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} dict1.update(dict2) print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4} # Example 2: Updating with key-value pairs dict1 = {'a': 1, 'b': 2} dict1.update(c=3, d=4)
  • 23.
    print(dict1) # Output:{'a': 1, 'b': 2, 'c': 3, 'd': 4} values() Returns a new object of the dictionary's values my_dict = {'a': 1, 'b': 2, 'c': 3} print(my_dict.values()) # Output: dict_values([1, 2, 3]) Table: Dictionary Method in Python Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys d=dict() for x in range(1,16): d[x]=x**2 print(d) Output {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225} DICTIONARY COMPREHENSION Dictionary comprehension is an elegant and concise way to create dictionaries. Syntax dictionary = {key: value for vars in iterable} Example square_dict = {num: num*num for num in range(1, 11)} print(square_dict) Output {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}