List String Tuple Sets Dictionary
List String Tuple Sets Dictionary
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Prerequisite/Recapitulations
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Objectives
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Introduction
List in Python is a fundamental data structure that serves as a container for holding an ordered collection of
items/objects.
• The items of a list need not be of same data type.
• We can retrieve the elements of a list using "index".
• List can be arbitrary mixture of types like numbers, strings and other lists as well.
• They are of variable size i.e they can grow or shrink as required
• They are mutable which means the elements in the list can be changed/modified
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Create and Access a List
Your task is to :
• Take an integer n as input from the user.
• Ask the user to enter n items one by one to store them in the list data structure.
• At the end just print the list.
One or more elements of a list can be deleted using The list remove(element) method is also used for this purpose.
the keyword del. This can as well delete the entire This method searches for the given element in the list and removes
list. the first matching element.
dlist = ['red', 'orange', 'blue', 'green', 'yellow', 'red'] remlist = ['red', 'orange', 'blue', 'green', 'yellow', 'red']
print(dlist) remlist.remove('green')
['red', 'orange', 'blue', 'green', 'yellow', 'red'] print(remlist)
del dlist[5] ['red', 'orange', 'blue', 'yellow', 'red']
print(dlist)
The pop(index) method removes and returns the item at index, if
['red', 'orange', 'blue', 'green', 'yellow']
index is provided.
del dlist[2:]
If index is not provided as an argument, then pop() method
print(dlist)
removes and returns the last element.
['red', 'orange']
plist = ['red', 'orange', 'blue', 'green', 'yellow', 'cyan']
del dlistT
elem = plist.pop()
The clear() method is to used to clear the contents print(elem)
of a list and make it empty. 'cyan'
plist.clear() elem = plist.pop(-1)
print(plist) print(elem)
[] 'yellow'
print(plist) ['red', 'orange', 'blue', 'green‘]
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Understand mutability in List and Indexing
Lists are mutable which means the items in it can be changed. Mutability involves altering specific data without
complete recreation. List items can be changed by assigning new values using the indexing operator ([ ]).
Example Description
a = [1, 2, 3, 4, 5] a[0:3] = [ ] print(a) # Output: Certain elements from a list can also be
[4, 5] removed by assigning an empty list to them
a = [1, 2, 3, 4, 5] a[0:0] = [20, 30, 45] print(a) # The elements can be inserted into a list by
Output: [20, 30, 45, 1, 2, 3, 4, 5] squeezing them into an empty slice at the desired location
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
List Slicing
List slicing is an operation that extracts a subset of elements Slices Example Description
from a list and creates a new list with them. a = [9, 8, 7, 6, 5, 4]
a[0:3] a[0:3] Print a part of list from index 0 to 2
[9, 8, 7]
Syntax for List slicing:
a[:4] Default start value is 0.
a[:4]
[9, 8, 7, 6] Prints the values from index 0 to 3
Listname[start:stop]
Listname[start:stop:steps] a[1:]
a[1:] Prints values from index 1 onwards
[8, 7, 6, 5, 4]
➢ default start value is 0 a[:]
a[:]
Prints the entire list
[9, 8, 7, 6, 5, 4]
a[2:2]
➢ default stop value is n -1 a[2:2]
[]
Prints an empty slice
a[0:6:2]
➢ [:] this will print the entire list a[0:6:2]
[9, 7, 5]
Slicing list values with step size 2
a[::-1]
a[::-1] Prints the list in reverse order
➢ [2:2] this will create an empty slice [4, 5, 6, 7, 8, 9]
a[-3:]
a[-3:] Prints the last 3 items in list
[6, 5, 4]
a[:-3]
a[:-3] Prints all except the last 3 items in list
[9, 8, 7]
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Built function and methods
Here is a list of built-in functions that can be applied on a list: 5. max(): Returns the item with the highest value from
1. all(): Returns True if all the items in the list have a true the list
value. print(max([1, 2, 3, 4, 5]))
print(all([' ', ',', '1', '2'])) 5
True 6. min(): Returns the item with the lowest value from
2. any(): Returns True if atleast one item in the list has a true the list.
value. print(min([1, 2, 3, 4, 5]))
print(any([' ', ',', '1', '2'])) 1
True 7. sorted(): Returns a sorted version of the given list,
3. enumerate(): Returns an enumerate object consisting of leaving the original list unchanged.
the index and the values of all items of the list as a tuple pair. origlist = [1, 5, 3, 4, 7, 9, 1, 27]
print(list(enumerate(['a','b','c','d','e']))) print(sorted(origlist)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')] [1, 1, 3, 4, 5, 7, 9, 27]
4. len(): It calculates the length of the list i.e., the number of 8. sum(): Returns the sum of all the elements of a list. It
elements in the list. works only on an integer list.
print(len(['a', 'b', 'c', 'd', 'e'])) print(sum([1, 5, 3, 4, 7, 9, 1, 27]))
5 57
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Built function and methods
reverse()
Reverse the order of elements of the list in place
x = ['z', 'f', 'e', 'a','b', 'g', 't']
x.reverse()
print(x)
['t', 'g', 'b', 'a', 'e', 'f', 'z']
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String in Python
Strings in python are represented with prefixing and suffixing the characters with quotation marks (either single quotes (')
or double quotes (")).
❖ Characters in a string are accessed using an index which is an integer (either positive or negative).
❖ It starts from 0 to n-1, where n is the number of characters in a string.
❖ Strings are immutable which means contents cannot be changed once they are created.
❖ The function input() in python is a string by default.
In computer programming, a string is a sequence of characters. Example: Python String
For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use single quotes or double quotes to represent a string in Python. For example, # create string type variables
name = "Python"
# create a string using double quotes print(name)
string1 = "Python programming" message = "I love Python."
# create a string using single quotes print(message)
string1 = 'Python programming‘
Output
Here, we have created a string variable named string1. Python
The variable is initialized with the string I love Python.
Python Programming.
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Operation on String
To access a specific character from a string, we use its position called Index which is enclosed within square brackets [].
Index value always starts with 0.
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Indexing on String
a = "HELLO"
print(a[0]) # prints the 0th index value, where Output will be 'H‘
At index '0', the character 'H' is present, so Indexing starts from the left and increments to the right.
print(a[-1]) # prints -1 index value, where Output will be 'O‘
At index '-1', the character 'O' is present, so Indexing starts from the right and increments to the left.
Given a string "This is my first String". Write the code to achieve the following.
print the entire string
print the character f using positive/forward indexing
print the character S using negative/backward indexing
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String Properties
Python Strings are immutable Python Multiline String
In Python, strings are immutable. That means the characters of a We can also create a multiline string in Python. For
string cannot be changed. this, we use triple double quotes """ or triple single
For example, quotes '''.
message = 'Hola Amigos'
message[0] = 'H' For example,
print(message) # multiline string
Output message = """
TypeError: 'str' object does not support item assignment Never gonna give you up
Never gonna let you down
However, we can assign the variable name to a new string. """
For example, print(message)
message = 'Hola Amigos' # assign new string to message variable Output
message = 'Hello Friends' Never gonna give you up
prints(message); # prints "Hello Friends“ Never gonna let you downIn
>>> greeting = 'Hello, world!' the above example, anything inside the enclosing
>>> new_greeting = 'J' + greeting[1:] triple-quotes is one multiline string.
>>> new_greeting
'Jello, world!'
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String Slicing
➢ Slicing will start from index and will go up to stop in step Output:
of steps. Hello World!
➢ Default value of start is 0, H
➢ Stop is last index of list llo
➢ And for step default is 1 llo World!
Hello World!Hello World!
Hello World!TEST
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Python Escape Sequence Characters
There are some characters that have a special meaning when used in a string. Code Description
But what do you do if you would like to insert that character in the string as is,
without invoking its special meaning? \' Single Quote
\” Double Quote
For understanding this, let us take a simple example. We use single quotes or
double quotes to define a string. Suppose, we define a string with single \ Backslash
quotes. The first occurrence of a single quote marks the start of the string and
the second occurrence marks the end of the string. Now, consider that we \n New Line
would like to have a single quote in our string. What do we do now? If we
\r Carriage Return
place a single quote just like that in the middle of the string, Python would
think that this is the end of the string, which is actually not. \t Tab
To insert these kinds of illegal characters, we need the help of a special \b Backspace
character like backslash \.
\f Form Feed
What is the escape character used in the below code? \ooo Octal Value
x = 'hello\'world'
\xhh Hex Value
print(x)
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String functions and methods
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String functions and methods
12. find() Finding the index of the first occurrence of a Syntax: String.startswith(„string‟)
string in another string Example:
Syntax: String.find(„string‟) >>> string="Nikhil Is Learning"
Example: >>> string.startswith('N')
>>> string="Nikhil Is Learning" True
>>> string.find('k') 15. endswith()
2 Determines if string or a substring of string (if starting
13. swapcase() Converts lowercase letters in a string to index beg and ending index end are given) ends with
uppercase and viceversa substring str; returns true if so and false otherwise.
Syntax: String.find(„string‟) Syntax: String.endswith(„string‟)
Example: Example:
>>> string="HELLO" >>> string="Nikhil Is Learning"
>>> string.swapcase() >>> string.startswith('g')
'hello' True
14. startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting Note:
index beg and ending index end are given) starts with All the string methods will be returning either true or
substring str; returns true if so and false otherwise. false as the result
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String functions and methods
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String functions and methods
print('a' in 'program') # True This new formatting syntax is powerful and easy to
print('at' not in 'battle') # False use. From now on, we will use f-Strings to print
strings and variables.
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Introduction to tuples
A tuple is similar to a list in Python, but it is immutable, meaning its elements cannot be changed after creation, providing a
fixed and ordered collection of values. Elements of a tuple are enclosed in parenthesis ( ).
Once a tuple has been created, addition or deletion of elements to a tuple is not possible due to its immutable nature.
Benefits of Tuple:
•Tuples are faster than lists.
•Since a tuple is immutable, it is preferred over a list to have the data write-protected.
•Tuples can be used as keys in dictionaries unlike lists.
Tuples can contain a list as an element and the elements of the list can be modified as we know that the lists are mutable.
The elements of a Tuple cannot be changed(immutable). Follow the given instructions and write the missing code
However, if the element itself is mutable like in the case of below
a list, its nested elements can be changed.
▪ The program takes input tuple with elements (a, b, c, d)
A tuple can also be reassigned with different values. ▪ Print the input tuple
▪ Add nested elements [1, 2, 3] to the tuple
mytup = ('a', 'b', 'c', 'd') ▪ change the nested element value from 2 to 4 and print
mytup = ('a', 'b', 'c', 'd', [1, 2, 3]) the resultant tuple
mytup[4][1] = 4
print(mytup) Sample Input and Output:
('a', 'b', 'c', 'd', [1, 4, 3])
mytup = ('r', 'e', 'a', 's', 's', 'i', 'g', 'n', 'e', 'd') mytup = ('a', 'b', 'c', 'd')
print(mytup) mytup = ('a', 'b', 'c', 'd', [1, 2, 3])
('r', 'e', 'a', 's', 's', 'i', 'g', 'n', 'e', 'd') mytup[4][1] = 4
del mytup[-1] mytup = ('a', 'b', 'c', 'd', [1, 4, 3])
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Indexing in Tuples
As we know that the elements of a tuple cannot be Once a tuple is created, the elements can be accessed using
deleted but if the element itself is mutable like a list, its the index operator [ ] and also by using the indices starting
nested elements can be deleted. and also, we can delete from 0 to N - 1 where N is the total count of elements.
the entire tuple using del keyword. Let's see an example:
Negative indexing can also be used starting with -1 upto -
mytup = ('a', 'b', 'c', 'd', [1, 2, 3]) N where -1 refers to the last element in the tuple.
del mytup[4][2]
print(mytup) # Result: ('a', 'b', 'c', 'd', [1, 2]) If an invalid index is specified, then it will result in
del mytup[4] an IndexError.
Traceback (most recent call last):
File "<stdin>", line 1, in <module> mylist = [1, 2, 3, 'a', 'b', 6.75, "Python"]
TypeError: 'tuple' object doesn't support item deletion mytup = tuple(mylist)
print(mytup)
del mytup (1, 2, 3, 'a', 'b', 6.75, 'Python') # Result
print(mytup) # throws an error because mytup is deleted print(mytup[7])
Traceback (most recent call last): Traceback (most recent call last):
File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <module>
NameError: name 'mytup' is not defined IndexError: tuple index out of range
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Features of Tuples
One of Python's distinctive features is the ability to use a Swapping using tuple assignment:
tuple on the left side of an assignment statement. This a = 20
enables assigning multiple variables with multiple b = 50
values when there's a sequence on the left side. This type of (a, b) = (b, a)
assignment is commonly referred to as tuple assignment. print("Values after swapping:", a, b)
Values after swapping: 50 20
The only restriction for this is that the number of variables
on the left and values on the right of an assignment should Select all the correct statements from the given options:
be equal. Otherwise, it will return an error ValueError. ❑ The output of the following code: ('ac') * 2 is ('ac', 'ac').
❑ The output of the following code: ('ac',) * 2 is ('ac', 'ac').
Let's see some examples on this: ❑ (1, 2, 3) > (1, 0, 3) is True.
list1 = ['Python', 'is', 'fun'] ❑ t1 = tuple({1:10, 2:20}) will result in (10, 20).
var1, var2, var3 = list1
print(var1) # Result: 'Python'
print(var2) # Result: 'is'
print(var3) # Result: 'fun‘
a, b = 1, 2, 3
ValueError: too many values to unpack
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Tuples Functions
As we learnt earlier, tuple repetition is used to repeat a Take two inputs from the user: one to create a tuple and the
tuple n number of times. let's see an example on this. other as an integer n. Write a program to print the
mytup = (1, 2, 3, 'a', 'b', 6.75, 'Python') tuple n times.
print(mytup)
(1, 2, 3, 'a', 'b', 6.75, 'Python') Create another tuple with the user-given elements and
print(mytup * 0) concatenate the first tuple with the new tuple and print the
() result as shown in the example.
print(mytup * 2)
(1, 2, 3, 'a', 'b', 6.75, 'Python', 1, 2, 3, 'a', 'b', 6.75, 'Python') Sample Input and Output:
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Menbership of Tuples
x = (1, 2, 3, 4, 5)
print(2 in x)
True
print(8 not in x)
True
print(10 in x)
False
print(5 in x)
True
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Functions and Method of Tuples
List of functions that can be applied on tuple are given below: len()
It calculates the length of the tuple i.e., the number of
all() elements.
Returns True if all the items in the tuple has a True value. x = (1, 2, 3, 4, 5, 6)
print(all((' ', ',', '1', '2'))) # Result: True print(len(x)) # Result: 6
print(all((False,' ', ',', '1'))) # Result: False
Select all the correct statements from the given options:
any() ❑ enumerate() method starts an index from 0.
Returns True if atleast one item in the tuple has a True value. ❑ any(' ', ' ', ' ', '?') returns True as output.
print(any((' ', ',', '1', '2'))) # Result: True ❑ any() will return True as output.
print(any((False,' ', ',', '1', '2'))) # Result: True
print(any((False, False, False))) # Result: False max()
It returns the item with the highest value in the tuple.
enumerate()
Returns an enumerate object consisting of the index and print(max((1, 2, 3, 4, 5, 6))) # Result: 6
the value of all items of a tuple as pairs.
x = (1, 2, 3, 4, 5, 6) min()
print(tuple(enumerate(x))) It returns the item with the lowest value in the tuple.
((0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)) # Result print(min((1, 2, 3, 4, 5, 6))) # Result: 1
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Functions and Method of Tuples
sorted()
It returns a sorted result of the tuple as a list, with the Select all the correct statements from the given options:
original tuple unchanged.
❑ t = (3, 1, 2) sorted(t) returns (1, 2, 3)
origtup = (1, 5, 3, 4, 7, 9, 1, 27) ❑ tuple("hello") returns the output as ('h', 'e', 'l', 'l', 'o')
sorttup = sorted(origtup) ❑ print(min(("P", "y", "t", "h", "o", "n", " "))) will return the
print(sorttup) # Result: [1, 1, 3, 4, 5, 7, 9, 27] output as ' '
print(origtup) # Result: (1, 5, 3, 4, 7, 9, 1, 27)
sum()
It returns the sum of all elements in the tuple. It works only
on numeric values in the tuple and will error out if the tuple
contains any other type of data.
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Python Set
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Access of elements in Set
You can also use the pop(), method to remove an item, but this Example:
method will remove item. the last removed items are unordered, so s={40,10,30,20}
you will not know what item that gets removed. print(s)
print(s.pop())
The return value of the pop() method is the removed item. print(s.pop())
thisset = {"apple", "banana", "cherry"} print(s.pop())
x = thisset.pop() print(s)
print(x) print(s.pop())
print(thisset) print(s) # Empty set
print(s.pop())
The clear() method used to remove all elements from the set: KeyError Traceback (most recent
thisset = {"apple", "banana", "cherry"} OUTPUT: call last)
thisset.clear() {40, 10, 20, 30} <ipython-input-22-3f6a1609f80b>
print(thisset) 40 in <module>
10 7 print(s.pop())
The del keyword will delete the set completely: 20 8 print(s) # Empty set
thisset = {"apple", "banana", "cherry"} {30} 9 print(s.pop())
del thisset 30 KeyError: 'pop from an empty set'
print(thisset) set()
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Python Set Operations
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Indexing on Dictionary
The index operator i.e., [ ], is used along with the key to Each element in a dictionary can be iterated using a for-loop.
access an element in a dictionary. The key should be valid to Let us consider an example:
access the corresponding value. fruits = {1:'apple', 2:'orange', 3:'mango', 4:'grapes'}
for indx in fruits:
In case, an invalid/non-existent key is specified, then a Key- print(fruits[indx], end = ' ')
Error is returned. # Result: apple orange mango grapes
month = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6} The above code prints the values corresponding to each of the
print(type(month)) # Result: <type 'dict'> keys in the dictionary.
print(month['Apr']) # Result: 4
print(month['Dec']) The items() method of dictionary returns a list of (key,
Traceback (most recent call last): value) tuples for each of the key:value pairs of a dictionary.
File "<stdin>", line 1, in <module>
print(month['Dec']) This list can be used to iterate/loop over the dictionary.
KeyError: 'Dec' fruits = {1:'apple', 2:'orange', 3:'mango', 4:'grapes'}
When the specified key does not exist in the dictionary, to print(fruits.items()) # Result: [(1, 'apple'), (2, 'orange'), (3,
avoid the error shown, the get() method can be used. It 'mango'), (4, 'grapes')]
returns None instead of Key-Error, when the key is not for key, value in sorted(fruits.items()):
found. print(key,value)
print(month.get('Dec')) # Result: None # Result: 1 apple 2 orange 3 mango 4 grapes
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Delete from Dictionary
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Mutable Dictionary
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Function and Method of Dictionary
Let's learn about the list of functions that can be applied to sorted():
a dictionary: It returns a sorted list of dictionary's keys.
all(): dict1 = {2:'alpha', 3:'beta', 1:'gamma', 4:'music', 6:'video'}
It returns True if all the keys of a dictionary are true, else sortlist = sorted(dict1)
returns False. print(sortlist) # Result: [1, 2, 3, 4, 6]
dict1 = {1:'alpha', 2:'beta', 3:'gamma', 4:'music'}
print(all(dict1)) # Result: True
dict2 = {1:'alpha', 2:'', '':'gamma', 4:'music'}
print(all(dict2)) # Result: False
any():
It returns True if atleast a single key of a dictionary
is True else False.
dict2 = {1:'alpha', 2:'', '':'gamma', 4:'music'}
print(any(dict2)) # Result: True
len():
It calculates the length of the dictionary i.e., the number of
key: value pairs.
dict1 = {1:'alpha', 2:'beta', 3:'gamma', 4:'music'}
print(len(dict1)) # Result: 4
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Function and Method of Dictionary
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Practice Questions
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
References
TEXT BOOKS
1.Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition,
Updated for Python 3, Shroff/O‘Reilly Publishers, 2016.
2.R. Nageswara Rao, “Core Python Programming”, dreamtech
3. Python Programming: A Modern Approach, Vamsi Kurama, Pearson
REFERENCE BOOKS:
1. Core Python Programming, W.Chun, Pearson.
2. Introduction to Python, Kenneth A. Lambert, Cengage
3. Learning Python, Mark Lutz, Orielly
ONLINE :
https://www.programiz.com/python-programming/list
https://www.geeksforgeeks.org/python-data-types/?ref=lbp
https://www.youtube.com/watch?v=HvA7I0l0nqI
https://galgotias.codetantra.com
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)