0% found this document useful (0 votes)
6 views100 pages

Unit 3

Unit 3 of the Python Programming course covers Python data structures, focusing on strings, lists, tuples, sets, and dictionaries. It details string characteristics, including indexing, slicing, concatenation, and built-in methods for string manipulation. The unit emphasizes the immutability of strings and provides examples of various string operations and functions.

Uploaded by

Krish Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views100 pages

Unit 3

Unit 3 of the Python Programming course covers Python data structures, focusing on strings, lists, tuples, sets, and dictionaries. It details string characteristics, including indexing, slicing, concatenation, and built-in methods for string manipulation. The unit emphasizes the immutability of strings and provides examples of various string operations and functions.

Uploaded by

Krish Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

PYTHON PROGRAMMING

UNIT 3
Python Data Structure
Python Strings Lists and Tuples Sets Dictionaries 2/100

Unit 3 Outline I

1 Python Strings

2 Lists and Tuples

3 Sets

4 Dictionaries
Python Strings Lists and Tuples Sets Dictionaries 3/100

1 Python Strings

2 Lists and Tuples

3 Sets

4 Dictionaries
Python Strings Lists and Tuples Sets Dictionaries 4/100

Python Strings
The python string data type is a sequence made up of one or more
individual characters, where a character could be a letter, digit,
whitespace or any other symbol.
Python treats strings as contiguous series of characters delimited by
single, double or triple quotes.
Multi-line strings are specified using triple quotes.
1 >>> a = 'Hello'
2 >>> b = "Hello"
3 >>> c = '''Hello everyone.
4 ... "Welcome to the world of 'python'."
5 ... Happy learning.'''
6 >>> print(c)
7 Hello everyone.
8 "Welcome to the world of 'python'."
9 Happy learning.

Python has built in string class str that has many useful features.
Python Strings Lists and Tuples Sets Dictionaries 5/100

Python Strings
A string is a sequence of characters
Lowercase and uppercase characters have different encoding and
hence strings are case-sensitive
1 >>> a = 'a'
2 >>> b = 'abc'
3 >>> name = 'python'
4 >>> type(name)
5 <class str'>
6 >>> print(name)
7 python
Python Strings Lists and Tuples Sets Dictionaries 6/100

Python Strings
Escape sequences (\’,\”,\\, \n, \t etc.) are used to print certain
characters such as (’, ,”, \, newline, tab etc)

1 >>> print('what's your name.')


2 SyntaxError: invalid syntax
3 >>> print('what\'s your name.')
4 what's your name.
5 >>> print("welcome to \"Adani University\".")
6 welcome to "Adani University".
7 >>> print("Hello everyone. \n \"Welcome to the world of \'python\'.\"")
8 Hello everyone.
9 "Welcome to the world of 'python'."

If you want to display string as specified without handling escape


sequences than raw string is used by prefixing r or R to the string.

1 >>> print(r'what\'s your name.')


2 what\'s your name.
Python Strings Lists and Tuples Sets Dictionaries 7/100

Python Strings : Indexing


The characters of a string can be accessed through indexing
In python, all indexing is zero-based for example, typing name[0] into
the interpreter will cause it to display the string character 'p'
1 >>> name = 'python'
2 >>> name[0]
3 'p'
4 >>> name[5]
5 'n'
6 >>> name[6]
7 IndexError: string index out of range
Python Strings Lists and Tuples Sets Dictionaries 8/100

Python Strings : Indexing


Python uses negative numbers to access the characters at the end of
the string
Negative index number count back from the end of the string
1 >>> name = 'python'
2 >>> name[-1]
3 'n'
4 >>> name[-3]
5 'h'
Python Strings Lists and Tuples Sets Dictionaries 9/100

Python Strings : Slicing


The extraction of substrings (slice) from a string is called slicing
1 str = "PYTHON"
2 print("str[1:5] = ", str[1:5]) # characters starting at index 1
3 # and extending up to index 4
4 print("str[:6] = ", str[:6]) # defaults to the start of the string
5 print("str[1:] = ", str[1:]) # defaults to the end of the string
6 print("str[:] = ", str[:]) # defaults to the entire string
7 print("str[1:20] = ", str[1:20])# an index is too big is
8 # truncated down to length of string
9 OUTPUT
10 str[1:5] = YTHO
11 str[:6] = PYTHON
12 str[1:] = YTHON
13 str[:] = PYTHON
14 str[1:20] = YTHON
Python Strings Lists and Tuples Sets Dictionaries 10/100

Python Strings : Slicing


Slicing can be done on a string using negative indexes starting with
the lower number first as it occurs in the string
1 str = "PYTHON"
2 print("str[-2:] = ", str[-2:]) # second last and last character
3 # accessed
4 print("str[:-2] = ", str[:-2]) # All character excluding second
5 # last character
6 print("str[-5:-2] = ", str[-5:-2]) # character from second upto
7 # second last are accessed
8 OUTPUT
9 str[-2:] = ON
10 str[:-2] = PYTH
11 str[-5:-2] = YTH
Python Strings Lists and Tuples Sets Dictionaries 11/100

Python Strings : Slicing With Stride


In slicing operation, third argument can be specified as the stride,
which refers to number of characters to move forward after the first
character is retrieved from the string
1 str = "Welcome to the world of Python"
2 print("str[2:10] = ", str[2:10]) # default stride is 1
3 print("str[2:10:1] = ", str[2:10:1]) # same as stride = 1
4 print("str[2:10:2] = ", str[2:10:2]) # skips every alternate character
5 print("str[2:13:4] = ", str[2:13:4]) # skips every fourth character
6
7 OUTPUT
8 str[2:10] = lcome to
9 str[2:10:1] = lcome to
10 str[2:10:2] = loet
11 str[2:13:4] = le
Python Strings Lists and Tuples Sets Dictionaries 12/100

Python Strings : Slicing With Stride


To print the string in reverse order, -1 is used as stride
1 str = "Welcome to the world of Python"
2 print("str[::3] = ", str[::3])
3 print("str[::-1] = ", str[::-1]) # To set string in reverse order
4 print("str[::-3] = ", str[::-3])
5
6 OUTPUT
7 str[::3] = WceohwloPh
8 str[::-1] = nohtyP fo dlrow eht ot emocleW
9 str[::-3] = nt r ttml
Python Strings Lists and Tuples Sets Dictionaries 13/100

Python Strings : Concatenation


The word concatenate means to join together
In python several operations can be performed on strings using
built-in functions and overloaded operators
To join two strings, + operator is used

1 >>> s1 = "red"
2 >>> s2 = "apple"
3 >>> len(s1) # find length of string 's1'
4 3
5 # concatenate two strings and assign it to 's3'
6 >>> s3 = s1 + ' ' + s2
7 >>> print(s3)
8 red apple
9 >>> print("Hello " + str(1234))
10 Hello 1234
11 >>> print("Hello ", str(1234))
12 Hello 1234
Python Strings Lists and Tuples Sets Dictionaries 14/100

Python Strings : Appending


Append mean to add something at the end
In Python, a string can be added at the end of another string using
+= operator

1 str = "Hello, "


2 name = input("\n Enter your name : ")
3 str += name
4 str += ". Welcome to Python Programming."
5 print(str)
6
7 OUTPUT
8 Enter your name : xyz
9 Hello, xyz. Welcome to Python Programming.
Python Strings Lists and Tuples Sets Dictionaries 15/100

Python Strings : Repeating


To repeat a string n number of times * operator is used

1 str = "Hello "


2 print(str * 3)
3 print('*'*10)
4
5 OUTPUT
6 Hello Hello Hello
7 **********
Python Strings Lists and Tuples Sets Dictionaries 16/100

Python Strings : Immutable


Python strings are immutable which means that once created they
cannot be changed.
Whenever we modify an existing string variable, a new string is
created
id() function return the memory address of the object stored in
memory
Output
1 str1 = "Hello"
2 print("str1 is : ", str1)
3 print("ID of str1 is : ", id(str1))
4 str2 = "World"
5 print("str2 is : ", str2)
6 print("ID of str2 is : ", id(str2))
7 str1 += str2
8 print("str1 after concatenation is : ", str1)
9 print("ID of str1 is : ", id(str1))
10 str3 = str1
11 print("str3 is : ", str3)
12 print("ID of str3 is : ", id(str3))
Python Strings Lists and Tuples Sets Dictionaries 17/100

Python Strings : ord() and chr() functions


The ord() function return the ASCII code of the character and
chr() function returns the character represented by ASCII number

1 ch = 'R'
2 print(ord(ch))
3 print(chr(82 + 32))
4 print(ord('a'))
5 print(chr(ord('a') - 32))
6
7 OUTPUT
8 82
9 'r'
10 97
11 'A'
Python Strings Lists and Tuples Sets Dictionaries 18/100

Python Strings : Iteration


String is a sequence of character and hence it can be iterated using
for loop
1 str = "Welcome to Python"
2 for i in str:
3 print(i, end = ' ')
4
5 OUTPUT
6 W e l c o m e t o P y t h o n

String can be iterated either using an index or by using each character


in the string
1 str = "Welcome to Python"
2 for i in range(len(str)):
3 print(str[i], end = ' ')
4
5 OUTPUT
6 W e l c o m e t o P y t h o n
Python Strings Lists and Tuples Sets Dictionaries 19/100

Python Strings : Iteration


String can also be iterated using while loop

1 str = "Welcome to Python"


2 index = 0
3 while index < len(str):
4 letter = str[index]
5 print(letter, end = ' ')
6 index += 1
7
8 OUTPUT
9 W e l c o m e t o P y t h o n
Python Strings Lists and Tuples Sets Dictionaries 20/100

Python Strings : Comparision


String can be iterated using relational (or comparison) operators.
The operator compare the strings by using lexicographical order i.e.
using ASCII value of the characters

1 >>> "Abc" == "Abc"


2 True
3 >>> "AbC" != "Abc"
4 True
5 >>> "AbC" <> "Abc" # not equal to
6 True
7 >>> "abc" > "Abc"
8 True
9 >>> "talks" < "talk"
10 False
Python Strings Lists and Tuples Sets Dictionaries 21/100

Python Strings : Methods and Functions


Python includes many string operations called methods
1 # input function is used to accept string from an user
2 >>> name = input("Enter name : ")
3 Enter name : Adani University
4 >>> len(name)
5 16
6 # split method to obtain a list of words
7 >>> words = name.split()
8 >>> words
9 ['Adani', 'University']
10 >>> cap_name = name.upper() # to get string in uppercase
11 >>> print("Institute : ", cap_name)
12 Institute : ADANI UNIVERSITY
13 >>> name.find("Uni") # to find "Uni" word in name
14 6
15 >>> joined_words = " ".join(words) # to join list of words
16 Adani University
17 >>> name.count('ni')
18 2
Python Strings Lists and Tuples Sets Dictionaries 22/100

Python Strings : Methods and Functions

Function Usage

capitalize() To capitalize first letter of the string


count(str, beg, end) Counts number of times str occurs in a string
find(str, beg, end) Checks if str is present in the sring. If found, it returns True and
False otherwise
index(str, beg, end) Same as find but raises an exception if str is not found
isalnum() Return True if string has at least 1 character abd every character
is either number or alphabet and False otherwise
isalpha() Returns True if string has at least 1 character and every character
is an alphabet and False otherwise
isdigit() Returns True if string contains only digits and False otherwise
islower() Returns True if string has at least 1 character and every character
is a lowercase alphabet and False otherwise
isupper() Returns True if string has at least 1 character and every character
is an uppercase alphabet and False otherwise
lower() Converts all characters in the string into lowercase
upper() Converts all characters in the string into uppercase
Python Strings Lists and Tuples Sets Dictionaries 23/100

Python Strings : Methods and Functions

Function Usage

len(string) Return the length of the string


strip() Removes all leading and trailing whitespace in string
max(str) Returns the highest alphabetical character (having highest ASCII
value) from the string str
min(str) Returns the lowest alphabetical character (lowest ASCII value)
from the string str
replace(old, new, max) Replaces all or max (if given) occurrences of old in string with
new
title() Returns string in title case
swapcase() Toggles the case of every character (uppercase character becomes
lowercase and vice versa)
split(delim) Returns a list of substrings separated by the specified delimiter.
If no delimiter is specified then by default it splits strings on all
whitespace characters
join(list) It is just opposite of split. The function joins a list of strings
using the delimiter with which the function is invoked
enumerate(str) Returns an enumerate object the lists the index and value of all
the characters in the string as pairs
Python Strings Lists and Tuples Sets Dictionaries 24/100

Python Strings : Methods and Functions


str = "hello" str = "he"
print(str.capitalize()) message = "helloworldhellohello"
print(message.count(str, 0, len(message)))
OUTPUT
Hello OUTPUT
3

str = "she is my best friend" str = "she is my best friend"


print(str.find("my",0,len(str))) print(str.index("mine",0,len(str)))

OUTPUT OUTPUT
7 ValueError: substring not found

str = "enrolno123" str = "enrolno123" str = "enrolno123"


print(str.isalnum()) print(str.isalpha()) print(str.isdigit())

OUTPUT OUTPUT OUTPUT


True False False
Python Strings Lists and Tuples Sets Dictionaries 25/100

Python Strings : Methods and Functions


str = "hello" str = "Hello" str = "HELLO"
print(len(str)) print(str.islower(str)) print(str.isupper(str))

OUTPUT OUTPUT OUTPUT


5 False True

str = "Hello" str = "Hello" str = " Hello "


print(str.lower()) print(str.upper()) print(str.strip())

OUTPUT OUTPUT OUTPUT


hello HELLO Hello

str = "hello hello hello" str = "The world is beautiful"


print(str.replace("he","Fo")) print(str.title())

OUTPUT OUTPUT
FOllo FOllo FOllo The World Is Beautiful
Python Strings Lists and Tuples Sets Dictionaries 26/100

Python Strings : Methods and Functions


str = "The World Is Beautiful" str = "abc,def, ghi,jkl"
print(str.swapcase()) print(str.split(','))

OUTPUT OUTPUT
tHE wORLD iS bEAUTIFUL ['abc', 'def', ' ghi', 'jkl']

str = "Hello" str = "Hello" str = " Hello "


print(str.lower()) print(str.upper()) print(str.strip())

OUTPUT OUTPUT OUTPUT


hello HELLO Hello

str = "hello hello hello" str = "The world is beautiful"


print(str.replace("he","Fo")) print(str.title())

OUTPUT OUTPUT
FOllo FOllo FOllo The World Is Beautiful
Python Strings Lists and Tuples Sets Dictionaries 27/100

1 Python Strings

2 Lists and Tuples

3 Sets

4 Dictionaries
Python Strings Lists and Tuples Sets Dictionaries 28/100

Data Structure
Data structure is a group of data elements that are put together
under one name
Data structure defines a particular way of storing and organizing data
in a computer so that it can be used efficiently
Sequence is the most basic data structure in Python
In the sequence data structure, each element has a specific index
The index value starts from zero and it automatically incremented for
the next element in the sequence
Python Strings Lists and Tuples Sets Dictionaries 29/100

Lists
List 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
The syntax for defining a list can be given as
List_variable = [val1, val2, ...]

>>> list_A = [1,2,3,4,5]


>>> print(list_A)
[1,2,3,4,5]
>>> list_B = ['A', 'b', 'C', 'd']
>>> print(list_B)
['A', 'b', 'C', 'd']
>>> list_C = ["Adani", "University"]
>>> print(list_C)
["Adani", "University"]
>>> list_D = [1,'a',"Abc"]
>>> print(list_D)
[1,'a',"Abc"]
Python Strings Lists and Tuples Sets Dictionaries 30/100

List : Access Values


Similar to strings, lists can also be sliced and concatenated
To access values (elements/items) in lists, square brackets are used to
slice along with the index or indices to get value stored at that index

num_list = [1,2,3,4,5,6,7,8,9,10]
print("num_list is : ", num_list)
print("First element in the list is ", num_list[0])
print("num_list[2:5] = ", num_list[2:5])
print("num_list[::2] = ", num_list[::2])
print("num_list[1::3] = ", num_list[1::3])

OUTPUT
num_list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
First element in the list is 1
num_list[2:5] = [3, 4, 5]
num_list[::2] = [1, 3, 5, 7, 9]
num_list[1::3] = [2, 5, 8]
Python Strings Lists and Tuples Sets Dictionaries 31/100

List : Updating Values


One or more elements of a list can be easily updated by giving slice
on the left-hand side of the assignment operator
New values can also be appended in the list or it can be removed
from the existing list using append() and del statement respectively
num_list = [1,2,3,4,5,6,7,8,9,10]
print("List is : ", num_list)
num_list[5] = 100
print("List after updation is : ", num_list)
num_list.append(200)
print("List after appending a value is ", num_list)
del num_list[3]
print("List after deleting a value is ", num_list)
del num_list[2:4]
print("List after deleting a value is ", num_list)

OUTPUT
List is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after updation is : [1, 2, 3, 4, 5, 100, 7, 8, 9, 10]
List after appending a value is [1, 2, 3, 4, 5, 100, 7, 8, 9, 10, 200]
List after deleting a value is [1, 2, 3, 5, 100, 7, 8, 9, 10, 200]
List after deleting a value is [1, 2, 100, 7, 8, 9, 10, 200]
Python Strings Lists and Tuples Sets Dictionaries 32/100

List : Nested Lists


Nested lists means a list within another list
List has elements of different data types which can include even a list

num_list = [1,9,11,13,15]
print("Original list : ", num_list)
num_list[2] = [3,5,7]
print("Updated list is : ", num_list)
print("num_list[2] : ", num_list[2])
print("num_list[2][1] : ", num_list[2][1])

OUTPUT
Original list : [1, 9, 11, 13, 15]
Updated list is : [1, 9, [3, 5, 7], 13, 15]
num_list[2] : [3, 5, 7]
num_list[2][1] : 5
Python Strings Lists and Tuples Sets Dictionaries 33/100

List : Cloning Lists


To modify a list and also to keep a copy of the original list, then a
separate copy of the list is created using cloning (not just the
reference)
Slice operation is used to clone a list

a = [1,2,3,4,5]
b = a # copies a list using reference
c = a[:] # copies a list using cloning
a[3] = 100
print("a = ", a)
print("b = ", b)
print("c = ", c)

OUTPUT
a = [1, 2, 3, 100, 5]
b = [1, 2, 3, 100, 5]
c = [1, 2, 3, 4, 5]
Python Strings Lists and Tuples Sets Dictionaries 34/100

List : Basic Operations


Operation Description Example Output

len Returns length of list len([1,2,3,4]) 4


concatenation Joins two lists [1,2,3] + [4,5,6] [1,2,3,4,5,6]
repetition Repeats elements in the ['a','b']*2 ['a','b','a','b']
list
in Checks if the value is 'a' in ['a','b','c'] True
present in the list
not in Checks if the value is not 3 not in [0,2,4,6] True
present in the list
Returns maximum a = [6,3,7,0,1,2]
max 7
value in the list max(a)
Returns minimum value a = [6,3,7,0,1,2]
min 0
in the list min(a)
Adds the values in the a = [1,2,3,4,5]
sum SUM=15
list that has numbers print("SUM=",sum(a))
converts an iterable List1 = list('Hello')
list (tuple, string, set, ['h','e','l','l','o']
print(list1)
dictionary) to a list
Returns a new sorted a = [3,4,1,2,7,8]
[1,2,3,4,7,8]
sorted list. The original list is b = sorted(a)
not sorted print(b)
Python Strings Lists and Tuples Sets Dictionaries 35/100

List : Methods

Method Description Syntax

append() Appends an element to the list list.append(obj)


count() Counts the number of times an element appears list.count(obj)
in the list
index() Returns the lowest index of obj in the list. Gives list.index(obj)
a ValueError if obj is not present in the list
insert() Inserts obj at the specified index in the list list.insert(index,obj)
pop() Removes the element at the specified index from list.pop([index])
the list. index is an optional parameter. If no
index is specified then removes the last object
(element) from the list
remove() Removes or deletes obj from the list. ValueError list.remove(obj)
is generated if obj is not present in the list
reverse() Reverses the elements in the list list.reverse()
sort() Sorts the elements in the list list.sort()
extend() Adds the elements in the list to the end of an- list1.extend(list2)
other list. similar to + and += operation
Python Strings Lists and Tuples Sets Dictionaries 36/100

List : Methods
a = [6,3,1,0,1,2,3,1] a = [6,3,7,0,1,2,4,9]
print(a.count(1)) a.append(10)
print(a)
OUTPUT
3 OUTPUT
[6,3,7,0,1,2,4,9,10]

a = [6,3,7,0,3,7,6,0] a = [6,3,7,0,3,7,6,0]
print(a.index(7)) a.insert(3,100)
print(a)
OUTPUT
2 OUTPUT
[6,3,7,100,0,3,7,6,0]

a = [6,3,7,0,1,2,4,9] a = [6,3,7,0,1,2,4,9] a = [6,3,7,0,1,2,4,9]


print(a.pop()) a.remove(0) a.reverse()
print(a) print(a) print(a)

OUTPUT OUTPUT OUTPUT


9 [6,3,7,1,2,4,9] [9,4,2,1,0,7,3,6]
[6,3,7,0,1,2,4]
Python Strings Lists and Tuples Sets Dictionaries 37/100

List : Methods
insert(), remove() and sort() methods only modify the list and do not
return any value
sort() method uses ASCII values to sort the values in the list which
means uppercase letter comes before lowercase letters and numbers
comes even before the uppercase letters

list1 = [1, 'a', "abc", 2, 'B', "Def"]


list1.sort()
print(list1)

OUTPUT
[1, 2, 'B', 'Def', 'a', 'abc']
Python Strings Lists and Tuples Sets Dictionaries 38/100

List : Stack
Stack is a linear data structure in which elements are added and
removed from one end.
Stack is called a LIFO (Last-In-First-Out) data structure, as the
element that was inserted last is the first one to be taken out.
A stack supports three basic operations : push, pop and peep (or
peek).
The push operation adds an element at the end of the stack.
The pop operation removes the last element from the stack.
The peep operation returns the last value of the last element of the
stack (without deleting it).
Python Strings Lists and Tuples Sets Dictionaries 39/100

List : Stack
In python, the list methods make it very easy to use list as a stack.
To push an element in the stack, append() method, to pop an element
pop() method and for peep operation the slicing operation can be use

stack = [1,2,3,4,5,6]
print("Original stack is : ", stack)
stack.append(7)
print("Stack after push operation is : ", stack)
stack.pop()
print("Stack after pop operation is : ", stack)
last_element_index = len(stack) - 1
print("Value obtained after peep operation is : ",
stack[last_element_index])

OUTPUT
Original stack is : [1, 2, 3, 4, 5, 6]
Stack after push operation is : [1, 2, 3, 4, 5, 6, 7]
Stack after pop operation is : [1, 2, 3, 4, 5, 6]
Value obtained after peep operation is : 6
Python Strings Lists and Tuples Sets Dictionaries 40/100

List : Queue
A queue is FIFO (First-In-First-Out) data structure in which the
element that is inserted first is the first one to be taken out
The element in a queue are added at one end and removed from the
other end
Queue supports three basic operations - insert, delete and peep
In python, queue can be implemented by using append() method to
insert an element at the end of the queue, pop() method with an
index 0 to delete the first element from the queue and slice operation
to print the value of the last element in the queue
Python Strings Lists and Tuples Sets Dictionaries 41/100

List : Queue

queue = [1,2,3,4,5,6]
print("Original queue is : ", queue)
stack.append(7)
print("Queue after insertion is : ", queue)
stack.pop(0)
print("Queue after deletion is : ", queue)
last_element_index = len(stack) - 1
print("Value obtained after peep operation is : ",
queue[len(queue) - 1])

OUTPUT
Original queue is : [1, 2, 3, 4, 5, 6]
Queue after insertion is : [1, 2, 3, 4, 5, 6, 7]
Stack after deletion is : [2, 3, 4, 5, 6, 7]
Value obtained after peep operation is : 7
Python Strings Lists and Tuples Sets Dictionaries 42/100

List Comprehensions
List comprehensions help programmers to create lists in a concise way.
This is mainly beneficial to make new lists where each element is
obtained by some operations to each member of another sequence or
iterable.
List comprehension is also used to create a subsequence of those
elements that satisfy certain conditions.
List comprehensions having the following syntax
List = [expression for variable in sequence if condition]

cubes = [i**3 for i in range(11)]


print(cubes)

OUTPUT
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Python Strings Lists and Tuples Sets Dictionaries 43/100

List Comprehensions
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)]

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = [x if x != "banana" else "orange" for x in fruits]
print(newlist)

OUTPUT
['apple', 'orange', 'cherry', 'kiwi', 'mango']

matrix = [[j for j in range(3)] for i in range(3)]


print(matrix)
OUTPUT
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Python Strings Lists and Tuples Sets Dictionaries 44/100

Lists : Looping
Python’s for and in constructs are extremely useful when working
with lists

# program to find the sum and mean of elements in a list


num_list = [1,2,3,4,5,6,7,8,9,10]
sum = 0
for i in num_list:
sum += i
print("Sum of elements in the list =", sum)
print("Average of elements in the list =",
float(sum/float(len(num_list))))

OUTPUT
Sum of elements in the list = 55
Average of elements in the list = 5.5
Python Strings Lists and Tuples Sets Dictionaries 45/100

Lists : Looping
enumerate() function is useful when to print both index as well as
an item in the list
enumerate() function returns an enumerate object which contains
the index and value of all the items of the list as a tuple

num_list = [1,2,3,4,5]
for index, i in enumerate(num_list):
print(i, " is at index : ", index)

OUTPUT
1 is at index : 0
2 is at index : 1
3 is at index : 2
4 is at index : 3
5 is at index : 4
Python Strings Lists and Tuples Sets Dictionaries 46/100

Lists : Looping
To print index, range() function can also be used

num_list = [1,2,3,4,5]
for i in range(len(num_list)):
print("index : ", i)

OUTPUT
index : 0
index : 1
index : 2
index : 3
index : 4
Python Strings Lists and Tuples Sets Dictionaries 47/100

Lists : Looping
The built-in iter() function creates an iterator which can be used to
loop over the element of the list
The iterator fetches the value and then automatically points to the
next element in the list when used with the next() method

num_list = [1,2,3,4,5]
it = iter(num_list)
for i in range(len(num_list)):
print("Element at index ", i, " is : ", next(it))

OUTPUT
Element at index 0 is : 1
Element at index 0 is : 2
Element at index 0 is : 3
Element at index 0 is : 4
Element at index 0 is : 5
Python Strings Lists and Tuples Sets Dictionaries 48/100

Lists : filter() function


The filter() function constructs a list from those elements of the
list for which a function returns True
The syntax of the filter() function is given as:
filter(function, sequence)
If sequence is a string, Unicode or a tuple, then result will be of the
same type, otherwise list will be returned

def check(x):
if (x % 2 == 0 or x % 4 == 0):
return 1
# call check() for every value between 2 to 21
evens = list(filter(check, range(2,22)))
print(evens)

OUTPUT
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Python Strings Lists and Tuples Sets Dictionaries 49/100

Lists : filter() function

# WAP that has a list of both positive and negative numbers. Create
# another list using filter() that has only positive values

def is_positive(x):
if x > 0:
return x

num_list = [10, -20, 30, -40, 50, -60, 70, -80, 90, -100]
pos_list = list(filter(is_positive, num_list))
print("Positive value list = ", new_list)

OUTPUT
Positive value list = [10, 30, 50, 70, 90]
Python Strings Lists and Tuples Sets Dictionaries 50/100

Lists : map() function


The map() function applies a particular function to every element of
a list.
The syntax of map() is similar to filter() function
The map() function calls function(items) for each item in the
sequence and returns a list if the return values

def add_2(x):
x += 2
return x
num_list = [1, 2, 3, 4, 5, 6, 7]
print("Original list is : ", num_list)
new_list = list(map(add_2, num_list))
print("Modified list is : ", new_list)

OUTPUT
Original list is : [1, 2, 3, 4, 5, 6, 7]
Modified list is : [3, 4, 5, 6, 7, 8, 9]
Python Strings Lists and Tuples Sets Dictionaries 51/100

Lists : map() function


More than one sequence can also be passed in the map() function
However, the function must have as many arguments as there are
sequences and if one of the sequence is shorter than the other then
None will be passed

def add(x,y):
return x+y
list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
list3 = list(map(add, list1, list2))
print("Sum of ", list1, " and ", list2, " = ", list3)

OUTPUT
Sum of [1, 2, 3, 4, 5] and [6, 7, 8, 9, 10] = [7, 9, 11, 13, 15]
Python Strings Lists and Tuples Sets Dictionaries 52/100

Lists: Example
WAP to print index at which a particular value exists in the list. If
the value exists at multiple locations in the list, then print all the
indices. Also, count the number of times that value is repeated in
the list.
Python Strings Lists and Tuples Sets Dictionaries 53/100

Lists: Example
WAP to print index at which a particular value exists in the list. If
the value exists at multiple locations in the list, then print all the
indices. Also, count the number of times that value is repeated in
the list.

num_list = [1,2,3,4,5,6,5,4,3,2,1]
num = int(input("Enter the value to be searched : "))
i = 0
count = 0
while i < len(num_list):
if num == num_list[i]:
print(num, " found at index ", i)
count += 1
i += 1
print(num, " appears ", count, " times in the list")

OUTPUT
Enter the value to be searched : 4
4 found at index 3
4 found at index 7
4 appears 2 times in the list
Python Strings Lists and Tuples Sets Dictionaries 54/100

Tuple
Tuple is another data structure in Python similar to lists but differ in
two things
- A tuple is a sequence of immutable objects which means that the
value cannot be changed in a tuple
- Tuple use parentheses to define its elements whereas lists uses square
brackets
Tuple can be created by different comma-separated values within a
parentheses
Tup = (val_1, val_2, ...)
Any set of multiple, comma-separated values written without an
brackets [] (for list) and parantheses () (for tuple) etc. are treated as
tuples by default
Python Strings Lists and Tuples Sets Dictionaries 55/100

Tuple

Tup = () # creates an empty tuple


Tup = (5,) # creates a tuple with a single element
Tup = 1,2,3 # creates a tuple with three elements
print(Tup)
Tup1 = (1,2,3,4,5) # creates a tuple of integers
print(Tup1)
Tup2 = ('a','b','c','d') # creates a tuple of characters
print(Tup2)
Tup3 = ("abc", "def", "ghi") # creates a tuple of floating point numbers
print(Tup3)
Tup4 = (1, "abc", 2.3, 'd') # creates a tuple of mixed values
print(Tup4)

OUTPUT
(1,2,3)
(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd')
('abc', 'def', 'ghi')
(1, 'abc', 2.3, 'd')
Python Strings Lists and Tuples Sets Dictionaries 56/100

Tuple : Assignment

# an unnamed tuple of values assigned to values of another unnamed tuple


(val1, val2, val3) = (1,2,3)
print(val1, val2, val3)
Tup = (100, 200, 300)
(val1, val2, val3) = Tup
print(val1, val2, val3)
# expressions are evaluated before assignment
(val1, val2, val3) = (2+4, 5/3 + 4, 9%6)
print(val1, val2, val3)

OUTPUT
1 2 3
100 200 300
6 5.666667 3
Python Strings Lists and Tuples Sets Dictionaries 57/100

Tuple : Accesing Values

Tup = (1,2,3,4,5,6,7,8,9,10)
print("Tup[3:6] = ", Tup[3:6])
print("Tup[:4] = ", Tup[:4])
print("Tup[4:] = ", Tup[4:])
print("Tup[:] = ", Tup[:])

OUTPUT
Tup[3:6] = (4, 5, 6)
Tup[:4] = (1, 2, 3, 4)
Tup[4:] = (5, 6, 7, 8, 9, 10)
Tup[:] = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Python Strings Lists and Tuples Sets Dictionaries 58/100

Tuple : Updating Values


Tuple is immutable and hence the values in the tuple cannot be
changed.
Only value from the tuple can be extracted to form another tuple.

Tup1 = (1,2,3,4,5)
Tup2 = (6,7,8,9,10)
Tup3 = Tup1 + Tup2
print(Tup3)

OUTPUT
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Python Strings Lists and Tuples Sets Dictionaries 59/100

Tuple : Basic Operations

Operation Expression Output

Length len((1,2,3,4,5)) 5
Concatenation (1,2,3) + (4,5,6) (1,2,3,4,5,6)
Repetition ('Good..',)*3 ('Good..','Good..','Good..')
Membership 5 in (1,2,3,4,5) True
for i in (1,2,3,4,5):
Iteration 1 2 3 4 5
print(i,end= ' ')
Tup1 = (1,2,3,4,5)
Comparision Tup2 = (5,1,2,3,4) True
print(Tup1<Tup2)
Maximum max(1,0,3,8,2,9) 9
Minimum min(1,0,3,8,2,9) 0
tuple("Hello") ('H','e','l','l','o')
Convert to tuple
tuple([1,2,3,4,5]) (1,2,3,4,5)
Python Strings Lists and Tuples Sets Dictionaries 60/100

Tuple : Returning Multiple Values


A function can return only a single value but sometimes we may need
to return multiple values from a function
In such situations, it is preferable to group together multiple values
and return them together as tuple

def max_min(vals):
x = max(vals)
y = min(vals)
return (x,y)
vals = (99, 98, 90, 97, 89, 86, 93, 82)
(max_marks, min_marks) = max_min(vals)
print("Highest Marks = ", max_marks)
print("Lowest Marks = ", min_marks)

OUTPUT
Highest Marks = 99
Lowest Marks = 82
Python Strings Lists and Tuples Sets Dictionaries 61/100

Nested Tuples
It is possible to define a tuple inside another tuple and this is called a
nested tuple
List can also be defined within tuple

student_info = ("Janvi", ("CSE", 123), [94,95,96,97])


print("Name : " , student_info[0])
print("Class and Enrol Number : ", student_info[1])
print("Highest score in 4 subjects : ", student_info[2:])
student_info[2][1] = 98
print("Modified score in 4 subjects : ", student_info[2])

OUTPUT
Name : Janvi
Class and Enrol Number : ('CSE', 123)
Highest score in 4 subjects : ([94,95,96,97])
Modified score in 4 subjects : [94,98,96,97]
Python Strings Lists and Tuples Sets Dictionaries 62/100

Tuples : Count() Method


The count() method is used to return the number of elements with
a specific value in a tuple

a = "abcdxxxxabcdxxxxabcdxxxx"
a = tuple(a)
print("x appears ", a.count('x'), " times in a")
b = (1,2,3,1,2,3,1,2,3,1,2,3)
print("1 appears ", b.count(1), " times in b")

OUTPUT
x appears 12 times in a
1 appears 4 times in b
Python Strings Lists and Tuples Sets Dictionaries 63/100

List Comprehension and Tuples


The same concept used in list comprehension can be used to
manipulate the values in one tuple to create a new tuple.

def double(T):
return ([i*2 for i in T])

tup = 1,2,3,4,5
print("Original Tuple : ", tup)
print("Double values : ", double(tup))

OUTPUT
Original Tuple : (1, 2, 3, 4, 5)
Double values : [2, 4, 6, 8, 10]
Python Strings Lists and Tuples Sets Dictionaries 64/100

Variable-length Argument Tuples


The built-in functions like max(), min(), sum() etc. use
variable-length arguments since number of arguments passed to these
functions are not known in advance.
Variable-length arguments tuple is a striking feature in Python.
It allows a function to accept variable (different) number of
arguments.
In such cases, variable-length argument that begin with a ’*’ symbol
is known as gather and specifies a variable-length argument.

def display(*arg):
print(args)

t = (1,2,3)
display(t,1,2)

OUTPUT
((1, 2, 3), 4, 5)
Python Strings Lists and Tuples Sets Dictionaries 65/100

Tuples : zip() function


zip() is a built-in function that takes two or more sequences and zips
them into a list of tuples.
The tuple thus formed has one element from each sequence.

Tup = (1,2,3,4,5)
List1 = ['a','b','c','d','e']
print(list(zip(Tup, List1)))
List2 = ['a','b','c']
print(list(zip(Tup, List2)))
for i, char in zip(Tup,List2):
print(i, char)

OUTPUT
[(1,'a'), (2,'b'), (3,'c'), (4,'d'), (5,'e')]
[(1,'a'), (2,'b'), (3,'c')]
1 a
2 b
3 c
Python Strings Lists and Tuples Sets Dictionaries 66/100

Tuples : zip() function


enumerate() function can be used to print elements as well as their
indices

for index, element in enumerate('ABCDEFG'):


print(index, element)

OUTPUT
0 A
1 B
2 C
3 D
4 E
5 F
6 G
Python Strings Lists and Tuples Sets Dictionaries 67/100

Advantages of Tuple over List


Since tuples are immutable, iterating through tuples is faster than
iterating over a list. This means that a tuple performs better than a
list.
Tuple 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. (Data
can be read but cannot write to it)
Tuples can be used in place of lists where the number of values is
known and small.
If tuple is used as an argument to a function, then the potential for
unexpected behavior due to aliasing gets reduced.
Multiple values from a function can be returned using a tuple.
Tuples are used to format strings
Python Strings Lists and Tuples Sets Dictionaries 68/100

Tuples : Example
WAP that accepts different number of arguments and return sum of
only the positive values passed to it.
Python Strings Lists and Tuples Sets Dictionaries 69/100

Tuples : Example
WAP that accepts different number of arguments and return sum of
only the positive values passed to it.

def sum_pos(*args):
tot = 0
for i in args:
if i > 0:
tot += i
return tot

print("sum_pos(1,-9,2,-8,3,-7,4,-6,5) = ", sum_pos(1,-9,2,-8,3,-7,4,-6,5))

OUTPUT
sum_pos(1,-9,2,-8,3,-7,4,-6,5) = 15
Python Strings Lists and Tuples Sets Dictionaries 70/100

1 Python Strings

2 Lists and Tuples

3 Sets

4 Dictionaries
Python Strings Lists and Tuples Sets Dictionaries 71/100

Sets
Sets is another data structure in Python which is similar to the lists
but with a difference that sets are lists with no duplicate entries
Set is a mutable and an unordered collection of items in which
items can be easily added or removed from it
A set is created by placing all the elements inside curly brackets,
separated by comma or by using the built-in function set().
The syntax of creating a set can be given as
set_variable = {val1, val2, ...}

s = {1,2.0,"abc"}
print(s)
a = set([1,2,'a','b','def', 4.56])
print(a)

OUTPUT
set([1, 2.0, 'abc'])
set(['a', 1, 2, 'b', 4.56, 'def'])
Python Strings Lists and Tuples Sets Dictionaries 72/100

Sets
If we add the same element multiple times in a set, they are removed
because a set cannot have duplicate values

List1 = [1,2,3,4,5,6,5,4,3,2,1]
print(set(list1)) # list is converted into a set
Tup1 = ('a','b','c','d','b','e','a')
print(set(Tup1)) # tuple is converted into a set
str = "abcdefabcdefg"
print(set(str)) # string is converted into a set
# forms a set of words
print(set("She sells sea shells on the sea shore".split()))

OUTPUT
set([1, 2, 3, 4, 5, 6])
set(['a', 'c', 'b', 'e', 'd'])
set(['a', 'c', 'b', 'e', 'd', 'g', 'f'])
set(['on', 'shells', 'shore', 'She', 'sea', 'sells', 'the'])
Python Strings Lists and Tuples Sets Dictionaries 73/100

Sets
Python Strings Lists and Tuples Sets Dictionaries 74/100

Sets
Coders = set(["Arnav","Goransh","Mani","Parul"])
Analysts = set(["Krish","Mehak","Shiv", "Goransh","Mani"])
print("Coders : ", Coders)
print("Analysts : ", Analysts)
print("People working as Coders as well as Analysts : ",
Coders.intersection(Analysts))
print("People working as Coders or Analysts : ",
Coders.union(Analysts))
print("People working as Coders but not Analysts : ",
Coders.difference(Analysts))
print("People working as Analysts but not Coders : ",
Analysts.difference(Coders))
print("People working in only one of the groups : ",
Coders.symmetric_difference(Analysts))

OUTPUT
Coders : {'Mani', 'Arnav', 'Goransh', 'Parul'}
Analysts : {'Goransh', 'Krish', 'Mehak', 'Mani', 'Shiv'}
People working as Coders as well as Analysts : {'Mani', 'Goransh'}
People working as Coders or Analysts : {'Arnav', 'Goransh', 'Krish',
'Mehak', 'Mani', 'Shiv', 'Parul'}
People working as Coders but not Analysts : {'Arnav', 'Parul'}
People working as Analysts but not Coders : {'Shiv', 'Krish', 'Mehak'}
People working in only one of the groups : {'Krish', 'Mehak',
'Shiv', 'Arnav', 'Parul'}
Python Strings Lists and Tuples Sets Dictionaries 75/100

Set Operations
Operation Description Code Output

s.update([1,2,3,4,5])
Adds elements of set s provided t = set([6,7,8])
s.update(t) {1,2,3,4,5,6,7,8}
that all duplicates are avoided s.update(t)
print(s)
Adds element x to the set s s = set([1,2,3,4,5])
s.add(x) provided that all duplicates are s.add(6) {1,2,3,4,5,6}
avoided print(s)
Removes element x from set s. s = set([1,2,3,4,5])
s.remove(x) Returns KeyError if x is not s.remove(3) {1,2,4,5}
present print(s)
Same as remove() but does not s = set([1,2,3,4,5])
s.discard(x) give error if x is not present in s.discard(3) {1,2,4,5}
the set print(s)
Removes and returns any s = set([1,2,3,4,5])
s.pop() arbitrary element from s. s.pop() {2,3,4,5}
KeyError is raised if s is empty. print(s)
s = set([1,2,3,4,5])
Removes all elements from the
s.clear() s.clear() set()
set
print(s)
Python Strings Lists and Tuples Sets Dictionaries 76/100

Set Operations
Operation Description Code Output

s.update([1,2,3,4,5])
len(s) Returns the length of set 5
print(len(s))
Returns True if every s = set([1,2,3,4,5])
s.issubset(t) element in s is present in set t = set([1,2,3,4,5,6,7]) True
t and False otherwise s<=t
Returns True if every s = set([1,2,3,4,5])
element in t is present in set
s.issuperset(t) t = set([1,2,3,4,5,6,7]) False
s and False otherwise s.issuperset(t)
Returns a set that has s = set([1,2,3,4,5])
s.union(t) elements from both sets s t = set([1,2,3,4,5,6,7]) {1,2,3,4,5,6,7}
and t s|t
Returns a new set that has s = set([1,2,3,4,5])
elements which are common
s.intersection(t) t = set([1,2,3,4,5,6,7]) {1,2,3,4,5}
to both the sets s and t s&t
s = set([1,2,10,12])
Returns a new set that has t = set([1,2,3,4,10])
s.difference(t) {12}
elements in set s but not in t z = s - t
print(z)
Python Strings Lists and Tuples Sets Dictionaries 77/100

Set Operations
Operation Description Code Output

s = set([1,2,10,12])
Returns a new set with
s.symmetric_ t = set([1,2,3,4,5,6])
elements either in s or in t {3,4,5,6,10,12}
difference(t) but not both z = s^t
print(z)
s = set([1,2,3,4,5])
s.copy() Returns a copy of set s t = s.copy() {1,2,3,4,5}
print(t)
Returns True if all elements s = set([0,1,2,3,4])
all(s) in the set are True and False print(all(s)) False
otherwise
Returns True if any of the s = set([0,1,2,3,4])
any(s) elements in the set s is True. print(any(s)) True
Returns False if the set is
empty.
s = set([5,4,3,2,1,0])
Return a new sorted list
sorted(s) print(sorted(s)) [0,1,2,3,4,5]
from elements in the set.
Python Strings Lists and Tuples Sets Dictionaries 78/100

Sets
Since sets are unordered, indexing have no meaning in set data types.
Set operations do not allow users to access or change an element
using indexing or slicing.

1 s = {1,2,3,4,5}
2 print(s[0])
3
4 OUTPUT
5 Traceback (most recent call last):
6 File "C:\Python34\Try.py", line 2, in <module>
7 print(s[0])
8 TypeError: 'set' object does not support indexing

A set can be created from a list but a set cannot contain a list.
Python Strings Lists and Tuples Sets Dictionaries 79/100

1 Python Strings

2 Lists and Tuples

3 Sets

4 Dictionaries
Python Strings Lists and Tuples Sets Dictionaries 80/100

Dictionaries
Dictionary is a data structure in which values are stored 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 dictionary is

dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}

If many keys and values in dictionaries, then one key-value pair can
be written per line for easy reading and understanding.

dictionary_name = {key_1: value_1,


key_2: value_2,
key_3: value_3,
}
Python Strings Lists and Tuples Sets Dictionaries 81/100

Dictionaries
Dictionary keys are case-sensitive
While keys in the dictionary must be unique and be of any immutable
data types (like strings, numbers or tuples), there is no stringent
requirement for uniqueness and type of values i.e. values can be of
any type
Dictionaries are not sequences, rather they are mappings
Mappings are collection of objects that store objects by key instead
of by relative position
Python Strings Lists and Tuples Sets Dictionaries 82/100

Creating a Dictionaries
Empty dictionary can be created as
Dict = {}

A dictionary can also be created by specifying key-value pairs


separated by a colon in curly brackets
Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
print(Dict)

OUTPUT
{'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}

dict() function creates a dictionary from a sequence of key value


pairs
Dict([('Roll_No', '16/001'), ('Name', 'Arav'), ('Course', 'BTech')])
print(Dict)

OUTPUT
{'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
Python Strings Lists and Tuples Sets Dictionaries 83/100

Creating a Dictionaries
Dictionary comprehensions is another way of creating a dictionary.
A dictionary comprehension is a syntactic construct which creates a
dictionary based on existing dictionary
The syntax can be given as

D = {expression for variable in sequence [if condition]}

Dictionary comprehension given within curly brackets and it has three


parts - for loop, condition and expression
The expression generates elements of dictionary from items in the
sequence that satisfy the condition.

Dict = {x : 2*x for x in range(1,6)}


print(Dict)

OUTPUT
{1:2, 2:4, 3:6, 4:8, 5:10}
Python Strings Lists and Tuples Sets Dictionaries 84/100

Dictionary : Accessing Values


To access values in a dictionary, square brackets are used along with
the key to obtain its value
1 Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
2 print("Dict[Roll_No] = ", Dict['Roll_No'])
3 print("Dict[Name] = ", Dict['Name'])
4 print("Dict[Course] = ", Dict['Course'])
5
6 OUTPUT
7 Dict[Roll_No] = 16/001
8 Dict[Name] = Arav
9 Dict[Course] = BTech

KeyError is generated if an item accessed with a key not specified in


the dictionary.
1 print("Dict[Marks] = ", Dict['Marks'])
2
3 OUTPUT
4 Traceback (most recent call last):
5 File "C:\Python34/Try.py", line 2, in <module>
6 print("Dict[Marks] = ", Dict['Marks'])
7 KeyError: 'Marks'
Python Strings Lists and Tuples Sets Dictionaries 85/100

Dictionary : Adding Items


To add a new entry or key-pair in a dictionary, key-value pair needs to
be specified

dictionary_variable[key] = val

1 Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}


2 print("Dict[Roll_No] = ", Dict['Roll_No'])
3 print("Dict[Name] = ", Dict['Name'])
4 print("Dict[Course] = ", Dict['Course'])
5 Dict['Marks'] = 95 # new entry
6 print("Dict[Marks] = ", Dict['Marks'])
7
8 OUTPUT
9 Dict[Roll_No] = 16/001
10 Dict[Name] = Arav
11 Dict[Course] = BTech
12 Dict[Marks] = 95
Python Strings Lists and Tuples Sets Dictionaries 86/100

Dictionary : Modifying Items


An entry can be modified by overwriting the existing value

1 Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BE'}


2 print("Dict[Roll_No] = ", Dict['Roll_No'])
3 print("Dict[Name] = ", Dict['Name'])
4 print("Dict[Course] = ", Dict['Course'])
5 Dict['Marks'] = 95 # new entry
6 print("Dict[Marks] = ", Dict['Marks'])
7 Dict['Course'] = 'BTech' # Modifying an entry
8 print("Dict[Course] = ', Dict['Course'])
9
10 OUTPUT
11 Dict[Roll_No] = 16/001
12 Dict[Name] = Arav
13 Dict[Course] = BE
14 Dict[Marks] = 95
15 Dict[Course] = BTech
Python Strings Lists and Tuples Sets Dictionaries 87/100

Dictionary : Deleting Items


To delete one or more items, del keyword is used

1 Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}


2 print("Dict[Roll_No] = ", Dict['Roll_No'])
3 print("Dict[Name] = ", Dict['Name'])
4 print("Dict[Course] = ", Dict['Course'])
5 del Dict['Course'] # deletes a key-value pair
6 print("After deleting course : ", Dict)
7 Dict.clear() # deletes all entries
8 print("After clear(), Dictionary has no items : ", Dict)
9 del Dict # deletes the variable Dict from memory
10 print("Dict does not exist .....")
11
12 OUTPUT
13 Dict[Roll_No] = 16/001
14 Dict[Name] = Arav
15 Dict[Course] = BTech
16 After deleting course : {'Roll_No': '16/001', 'Name':'Arav'}
17 After clear(), Dictionary has no items : {}
18 Dict does not exist .....
Python Strings Lists and Tuples Sets Dictionaries 88/100

Dictionary : Deleting Items


pop() method can also be used to delete a particular key from the
dictionary

dict.pop(key [, default])

The pop() method removes an item from the dictionary and returns
its value and if the specified key is not present then default value is
returned.
Since default is optional, if default is not specified then KeyError is
generated.
Another method dict.popitem() randomly pops and returns an
item from the dictionary.
Python Strings Lists and Tuples Sets Dictionaries 89/100

Dictionary : Deleting Items

Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}


print("Name is : ", Dict.pop('Name')) # returns Name
print("Dictionary after popping Name is : ", Dict)
print("Marks is : ", Dict.pop('Marks', -1)) # returns default value
print("Dictionary after popping Marks is : ", Dict)
print("Randomly popping any item : ", Dict.popitem())
print("Dictionary after random popping is : ", Dict)

OUTPUT
Name is : Arav
Dictionary after popping Name is : {'Course': 'BTech', 'Roll_No': '16/001'}
Marks is : -1
Dictionary after popping Marks is : {'Course': 'BTech', 'Roll_No': '16/001'}
Randomly popping any item : ('Course', 'BTech')
Dictionary after random popping is : {'Roll_No': '16/001'}
Python Strings Lists and Tuples Sets Dictionaries 90/100

Dictionary : Deleting Items


Not even a single key can be duplicated in a dictionary.
If duplicate key is added, then the last assignment is retained

1 Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech',


2 'Name' : 'Kriti'}
3 print("Dict[Roll_No] = ", Dict['Roll_No'])
4 print("Dict[Name] = ", Dict['Name'])
5 print("Dict[Course] = ", Dict['Course'])
6
7 OUTPUT
8 Dict[Roll_No] = 16/001
9 Dict[Name] = Kriti
10 Dict[Course] = BTech
Python Strings Lists and Tuples Sets Dictionaries 91/100

Dictionary : Sorting Items


The keys() method of dictionary returns a list of all keys used in the
dictionary in an arbitrary order.
The sorted() function is used to sort the keys

1 Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}


2 print(sorted(Dict.keys()))
3
4 OUTPUT
5 ['Course', 'Name', 'Roll_No']
Python Strings Lists and Tuples Sets Dictionaries 92/100

Dictionary : Looping
It is possible to loop over a dictionary to access only values, only keys
and both using for loop.

1 Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}


2 print("KEYS : ", end = ' ')
3 for key in Dict:
4 print(key, end = ' ') # accessing only keys
5 print("\nVALUES : ", end = ' ')
6 for val in Dict.values():
7 print(val, end = ' ') # accessing only values
8 print("\nDICTIONARY : ", end = ' ')
9 for key, val in Dict.items():
10 print(key, val, "\t", end = ' ') # accessing keys and values
11
12 OUTPUT
13 KEYS : Roll_No Course Name
14 VALUES : 16/001 BTech Arav
15 DICTIONARY : Roll_No 16/001 Course BTech Name Arav
Python Strings Lists and Tuples Sets Dictionaries 93/100

Nested Dictionaries

Students = {'Shiv' : {'CS':90, 'DS':89, 'CSA':92},


'Sadhvi' : {'CS':91, 'DS':87, 'CSA':94},
'Krish' : {'CS':93, 'DS':92, 'CSA':88}}

for key, val in Students.items():


print(key, val)

print(Students['Shiv']['CS'])
print(Students['Sadhvi']['CSA'])

OUTPUT
Sadhvi {'CS':91, 'CSA':94, 'DS':87}
Krish {'CS':93, 'CSA':88, 'DS':92}
Shiv {'CS':90, 'CSA':92, 'DS':89}
90
94
Python Strings Lists and Tuples Sets Dictionaries 94/100

Dictionary : Built-in Functions and Methods


Operation : len(Dict)
Description : Returns the length of dictionary. That is number of items
(key-value pairs)
Example :
Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
print(len(Dict1))

OUTPUT
3

Operation : str(Dict)
Description : Returns a string representation of the dictionary
Example :

Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}


print(str(Dict1))

OUTPUT
{'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
Python Strings Lists and Tuples Sets Dictionaries 95/100

Dictionary : Built-in Functions and Methods


Operation : Dict.clear()
Description : Deletes all entries in the dictionary
Example :
Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
Dict1.clear()
print(Dict1)

OUTPUT
{}

Operation : Dict.iteritems()
Description : Used to iterate through items in the dictionary
Example :
Dict = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
for i,j in Dict.iteritems():
print(i,j)

OUTPUT
Course BTech
Name Arav
Roll_No 16/001
Python Strings Lists and Tuples Sets Dictionaries 96/100

Dictionary : Built-in Functions and Methods


Operation : Dict.copy()
Description : Returns a shallow copy of the dictionary i.e. dictionary
returned will not have a duplicate copy of Dict but will have the same
reference
Example :
Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
Dict2 = Dict1.copy()
print(Dict2 : ", Dict2)
Dict2['Name'] = 'Saesha'
print("Dict1 after modification : ", Dict1)
print("Dict2 after modification : ", Dict2)

OUTPUT
Dict2 : {'Roll_No': '16/001', 'Name': 'Arav', 'Course': 'BTech'}
Dict1 after modification : {'Course': 'BTech', 'Name': 'Arav',
'Roll_No': '16/001'}
Dict2 after modification : {'Course': 'BTech', 'Name': 'Saesha',
'Roll_No': '16/001'}
Python Strings Lists and Tuples Sets Dictionaries 97/100

Dictionary : Built-in Functions and Methods


Operation : Dict.fromkeys(seq[,val])
Description : Create a new dictionary with keys from seq and values set
to val. if no val is specified then, None is assigned as default value
Example :
Subjects = ['CSA', 'C++', 'DS', 'OS']
Marks = dict.fromkeys(Subjects,-1)
print(Marks)

OUTPUT
{'OS':-1, 'DS':-1, 'CSA':-1, 'C++':-1}

Operation : Dict.get(key)
Description : Returns the value for the key passed as argument. If key is
not present in dictionary, it will return the default value. If no default
value is specified then it will return None
Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
print(Dict1.get('Name'))

OUTPUT
Arav
Python Strings Lists and Tuples Sets Dictionaries 98/100

Dictionary : Built-in Functions and Methods


Operation : Dict.items()
Description : Returns a list of tuples (key-value pair)
Example :
Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
print(Dict1.items())

OUTPUT
[('Course', 'BTech'), ('Name', 'Arav'), ('Roll_No', '16/001')]

Operation : Dict.keys()
Description : Returns a list of keys in the dictionary

Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}


print(Dict1.keys())

OUTPUT
['Course', 'Name', 'Roll_No']
Python Strings Lists and Tuples Sets Dictionaries 99/100

Dictionary : Built-in Functions and Methods


Operation : Dict.values()
Description : Returns a list of values in dictionary
Example :
Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
print(Dict1.values())

OUTPUT
['BTech', 'Arav', '16/001']

Operation : Dict1.update(Dict2)
Description : Adds the key-value pairs to Dict2 to the key-value pairs
of Dict1
Dict1 = {'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech'}
Dict2 = {'Marks' : 90, 'Grade' : 'o'}
Dict1.update(Dict2)
print(Dict1)

OUTPUT
{'Roll_No' : '16/001', 'Name' : 'Arav', 'Course' : 'BTech',
'Marks' : 90, 'Grade' : 'o'}
Python Strings Lists and Tuples Sets Dictionaries 100/100

Difference between a List and a Dictionary


A list is an ordered set of items. But a dictionary is a data structure
that is used for matching one item (key) with another (value).
Indexing can be used in list to access a particular item. But these
index should be a number. In dictionary, any type (immutable) of
value can be used as an index.
Lists are used to look up a value whereas a dictionary is used to take
one value and look up another value and for this reason dictionary is
also known as lookup table
The key-value pair may not be displayed in the order in which it was
specified while defining the dictionary. This is because Python uses
complex algorithms (called hashing) to provide fast access to the
items stored in the dictionary. This also makes dictionary preferable
to use over a list of tuples.

You might also like