0% found this document useful (0 votes)
17 views45 pages

List String Tuple Sets Dictionary

Uploaded by

memogarh3
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)
17 views45 pages

List String Tuple Sets Dictionary

Uploaded by

memogarh3
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/ 45

Name of the School: School of Computer Science and Engineering

Course Code: E2UC102C Course Name: PROGRAMMING FOR PROBLEM-SOLVING

Data Types in Python


❖ List
❖ String
❖ Tuple
❖ Set
❖ Dictionary

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Prerequisite/Recapitulations

✓ Basic Programming and Logic knowledge


✓ Mathematics in 10th class

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Objectives

Upon completion of the course, students will be able to

✓ Read, write, execute by hand simple Python programs.


✓ Structure simple Python programs for solving problems.
✓ Decompose a Python program into functions.
✓ Represent compound data using Python lists, tuples, dictionaries.

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

Let us consider an example:


L1 = [56, 78.94, "India"]
In the above example, L1 is a list, which contains 3 elements.
The first element is 56 (integer), the second is 78.94 (float), third is "India" (string).
Select all the correct statements given below.
❑ All elements in a list should be of same data type.
❑ Lists are immutable.
❑ Lists are ordered and can contain other lists as elements.
❑ Indexing can be used with lists to access individual items only if there are no nested lists.

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Create and Access a List

A list is created by using square brackets [ ] to enclose elements separated by commas ,.


For example:
a = [1, 2, 3, 4, 5, 6, 7, 8]
print(a) # Output: [1, 2, 3, 4, 5, 6, 7, 8]
We can also use the list() constructor to create a list:
colors = list(("red", "blue", "green", "yellow"))
type(colors) # <class 'list'>
print(colors) # Output: ['red', 'blue', 'green', 'yellow']
To access elements in a list, we use the indexing operator [ ] with the index of the element.
• Indices range from 0 to N-1, where N is the number of elements in the list, when moving from left to right.
We can also access elements in reverse, from right to left.
• The starting index is -1, which points to the last element and it goes up to -N, where N is the total number
of elements.
• Trying to access an element beyond the index range will result in an error.
Examples:
print(a[0]) # Output: 1
print(a[-1]) # Output: 8
print(a[8]) # Returns: "IndexError" because valid indices are 0 to 7
print(a[-8]) # Output: 1
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Write the code to create 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.

Constraints: Test Case 1:


1 <= n <= 10 L1=[]
Sample Test case: Expected Output:
l=int(input())
3 for i in range(l):
Apple L1.append(input()) 3
123 print(L1)
banana Apple
['apple','123','banana'] 123
banana
Explanation:
The first line of input contains the integer n. ['Apple',·'123',·'banana']
Next n Lines, the input is taken.
Every input value is added to the list.
Print the result as an output
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Add elements to a List

Lists are mutable (changeable). Meaning we 2. Using extend()


can add and remove elements from a list. We use the extend() method to add all the items of an iterable
Python list provides different methods to add (list, tuple, string, dictionary, etc.) to the end of the list.
items to a list. For example,
numbers = [1, 3, 5]
1. Using append() even_numbers = [4, 6, 8]
The append() method adds an item at the end numbers.extend(even_numbers)
of the list. print("List after append:", numbers)
For example,
numbers = [21, 34, 54, 12] Output
print("Before Append:", numbers) List after append: [1, 3, 5, 4, 6, 8]
append(32) Here, numbers.extend(even_numbers) adds all the elements
print("After Append:", numbers) of even_numbers to the numbers list.

Output 3. Using insert()


Before Append: [21, 34, 54, 12] We use the insert() method to add an element at the specified index.
After Append: [21, 34, 54, 12, 32] numbers = [10, 30, 40] # insert an element at index 1 (second
position)
Here, append() adds 32 at the end of the array. numbers.insert(1, 20)
print(numbers) # [10, 20, 30, 40]
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Deleting or removing elements

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] = 100 print(a) # Output:


Changing a single element
[100, 2, 3, 4, 5]

a = [1, 2, 3, 4, 5] a[0:3] = [100, 100, 100]


Changing multiple elements
print(a) # Output: [100, 100, 100, 4, 5]

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

sort(key = None, reverse = False) copy()


Sort the items of the list in place in ascending order Return the shallow copy of the list
If the parameter reverse = True, then the list is sorted Equivalent to a[:]
in place in descending order.
x = ['z', 'f', 'e', 'a','b', 'g', 't']
x = ['z', 'f', 'e', 'a','b', 'g', 't'] y = x.copy()
x.sort() print(y)
print(x) ['z', 'f', 'e', 'a', 'b', 'g', 't']
['a', 'b', 'e', 'f', 'g', 't', 'z'] print(x is y)
x.sort(key = None, reverse = True) False
print(x)
['z', 't', 'g', 'f', 'e', 'b', 'a']

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

In Python, there are 5 fundamental operations which can be performed on strings:


1. Indexing
2. Slicing
3. Concatenation
4. Repetition
5. Membership
Let us learn about Indexing first.

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.

Python has two types of indexing:


➢ Positive Indexing: It begins from the first character of a string, starting with 0. This method helps in accessing
the string from the beginning.
➢ Negative Indexing: It begins from the last character of a string, starting with -1. This method helps in accessing
the string from the end.

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Indexing on String

Let us consider the below example:

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

Sample Input and Output:


This is my first String
f
S

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

String slices: For example:


A segment of a string is called a slice. Selecting a slice is str = 'Hello World!'
similar to selecting a character. print str # Prints complete string
print str[0] # Prints first character of the string
Subsets of strings can be taken using the slice operator ([ ] print str[2:5] # Prints characters starting from
and [:]) with indexes starting at 0 in the beginning of the 3rd to 5th
string and working their way from -1 at the end. print str[2:] # Prints string starting from 3rd
character print
Slice out substrings, sub lists, sub Tuples using index. str * 2 # Prints string two times
Syntax:[Start: stop: steps] print str + "TEST" # Prints concatenated string

➢ 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

There are many methods to operate on String. 9. replace(old, new [, max])


1. isalnum() Returns true if string has at least 1 character and all Replaces all occurrences of old in string with new
characters are alphanumeric and false otherwise. or at most max occurrences if max given.
Syntax: String.isalnum() Example:
2. isalpha() Returns true if string has at least 1 character and all >>> string="Nikhil Is Learning"
characters are alphabetic and false otherwise. >>> string.replace('Nikhil','Neha')
3. isdigit() Returns true if string contains only digits and false 'Neha Is Learning'
otherwise. 10. split() Splits string according to delimiter str (space if
4. islower() Returns true if string has at least 1 cased character not provided) and returns list of substrings;
and all cased characters are in lowercase and false otherwise. Syntax: String.split()
5. isnumeric() Returns true if a string contains only numeric Example:
characters and false otherwise. >>> string="Nikhil Is Learning"
6. isspace() Returns true if string contains only whitespace >>> string.split()
characters and false otherwise. ['Nikhil', 'Is', 'Learning']
7. istitle() Returns true if string is properly “titlecased” and 11. count() Occurrence of a string in another string
false otherwise. Example:
8. isupper() Returns true if string has at least one cased >>> string='Nikhil Is Learning'
character and all cased characters are in uppercase >>> string.count('i')
and false otherwise. 3

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

Compare Two Strings Join Two or More Strings


We use the == operator to compare two strings. If In Python, we can join (concatenate) two or more strings using
two strings are equal, the operator returns True. the + operator.
Otherwise, it returns False. greet = "Hello,
For example, name = "Jack"
str1 = "Hello, world!" result = greet + name # using + operator
str2 = "I love Python." print(result) # Output: Hello, Jack
str3 = "Hello, world!" In the above example, we have used the + operator to join two
# compare str1 and str2 strings: greet and name.
print(str1 == str2)
# compare str1 and str3 Iterate Through a Python String
print(str1 == str3) We can iterate through a string using a for loop.
Output: For example,
False greet = 'Hello' Output:
True # iterating through greet string H
for letter in greet: e
In the above example, print(letter) l
str1 and str2 are not equal. Hence, the result is False. l
str1 and str3 are equal. Hence, the result is True. o

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
String functions and methods

Python String Length Python String Formatting (f-Strings)


In Python, we use the len() method to find the length
of a string. Python f-Strings make it really easy to print values
and variables.
For example, For example,
greet = 'Hello' name = 'Cathy'
# count length of greet string country = 'UK'
print(len(greet)) print(f'{name} is from {country}')
# Output: 5
Output
String Membership Test Cathy is from UK
We can test if a substring exists within a string or not,
using the keyword in. Here, f'{name} is from {country}' is an f-string.

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.

Let's consider a example:


t1 = (1, 2, 3, [4, 5], 5) Functions Description Example
t1[3][0] = 42
(1, 2, 3, [42, 5], 5) # list elements can be changed Converts a a = (1, 2, 3, 4, 5) a =
list() given tuple list(a) print(a) [1, 2,
Select all the correct statements from the given options: into a list. 3, 4, 5]
❑ A tuple is a mutable list.
❑ Tuples are slower when compared to lists. Converts a a = [1, 2, 3, 4, 5] a =
❑ Tuples can be used as keys in dictionaries. tuple() given list tuple(a) print(a) (1,
❑ Elements of a tuple are enclosed in parenthesis. into a tuple. 2, 3, 4, 5)
❑ Addition and deletion of elements is possible in a tuple.
❑ It is possible to create tuples which contain mutable objects, such as lists.
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Tuples Immutable

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

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

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:

Tuple concatenation is used to link two tuples. This data1: 10,20,30,40,50


operation generates a new tuple with the contents of both value: 2
the tuples. Let's see an example on this: tuple * 2 = ('10', '20', '30', '40', '50', '10', '20', '30', '40', '50')
tuple1 = ('a', 'b', 'c', 'd') data2: 60,90
tuple2 = (1 , 2, 3, 4, 5) concatenation: ('10', '20', '30', '40', '50', '60', '90')
tuple3 = tuple1 + tuple2
print(tuple3)
('a', 'b', 'c', 'd', 1, 2, 3, 4, 5)

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Menbership of Tuples

Tuple membership test is used to verify if an element exists in a


Tuple or not.

Python provides two operators in and not in for this purpose.

The result of using these operators is a boolean


value True or False.

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.

print(sum((1, 5, 3, 4, 7, 9, 1, 27))) # Result: 57


print(sum((1, 3, 5, 'a', 'b', 4, 6, 7)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Python Set

Key features of Set Data Type:


A set is a collection of unique data. That is, elements of a
set cannot be duplicate. ❖ Duplicates are not allowed.
For example, ❖ Insertion order is not preserved. But we can sort the
Suppose we want to store information about student IDs. elements.
Since student IDs cannot be duplicate, we can use a set. ❖ Indexing and slicing not allowed for the set.
❖ Heterogeneous elements are allowed.
❖ Set objects are mutable i.e ., once we creates set
object we can perform any changes in that object
based on our requirement.
❖ We can represent set elements within curly braces
▪ If we want to represent a group of unique values as a and with comma separation.
single entity then we should go for set. ❖ We can apply mathematical operations like union,
▪ A set is a collection which is unordered and unindexed. intersection, difference etc. on set objects.
In Python sets are written with curly
▪ braces { }.
▪ A set 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.
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Create Set in Python

# create a set of integer type Create an Empty Set in Python


student_id = {112, 114, 116, 118, 115} Creating an empty set is a bit tricky. Empty curly braces {} will make
print('Student ID:', student_id) an empty dictionary in Python.
# create a set of string type To make a set without any elements, we use the set() function
vowel_letters = {'a', 'e', 'i', 'o', 'u'} without any argument. For example,
print('Vowel Letters:', vowel_letters) # create an empty set
# create a set of mixed data types empty_set = set()
mixed_set = {'Hello', 101, -2, 'Bye'} # create an empty dictionary
print('Set of mixed data types:', mixed_set) empty_dictionary = { }
# check data type of empty_set
Output print('Data type of empty_set:', type(empty_set))
Student ID: {112, 114, 115, 116, 118} # check data type of dictionary_set
Vowel Letters: {'u', 'a', 'e', 'i', 'o'} print('Data type of empty_dictionary', type(empty_dictionary))
Set of mixed data types: {'Hello', 'Bye', 101, -2} Output
Data type of empty_set: <class 'set'>
Note: Data type of empty_dictionary <class 'dict'>
When you run this code, you might get output Here,
in a different order. This is because the set has empty_set - an empty set created using set()
no particular order. empty_dictionary - an empty dictionary created using {}

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Access of elements in Set

Duplicate Items in a Set OUTPUT :


Let's see what will happen if we try to include duplicate <class 'set'>
items in a set. ---------------------------------------------------------------------------
TypeError
numbers = {2, 4, 6, 6, 2, 8} Traceback (most recent call last)
print(numbers) <ipython-input-3-87d1e6948aef> in <module>
1 s = {30,40,10,5,20} # In the output order not preserved
OUTPUT: 2 print(type(s))
{8, 2, 4, 6} 3 print(s[0])
Here, we can see there are no duplicate items in the TypeError: 'set' object is not subscriptable
set as a set cannot contain duplicates.
But you can loop through the set items using a for loop, or ask if a
Access Items specified value is present in a set, by using the in keyword.
You cannot access items in a set by referring to an Example
index, since sets are unordered the items has no index. Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
s = {30,40,10,5,20} # In the output order not preserved for x in thisset:
print(type(s)) print(x)
print(s[0]) print("banana" in thisset)
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Change, Add & Remove from Set

Change Items Get the Length of a Set


Once a set is created, you cannot change its items, but you can To determine how many items a set has, use the len()
add new items. method.
thisset = {"apple", "banana", "cherry"}
Creation of set objects using set() function: print(len(thisset)
We can create set objects by using set() function.
Syntax: s=set(any sequence) Remove Item
l = [10,20,30,40,10,20,10] To remove an specified item in a set, use the remove(), or
s=set(l) the discard() method.
print(s) # {40, 10, 20, 30} because duplicates are not allowed in
thisset = {"apple", "banana", "cherry"}
set
thisset.remove("banana")
Add Items print(thisset)
To add one item to a set use the add() method.
thisset = {"apple", "banana", "cherry"}
To add more than one item to a set use the update() method.
thisset.discard("banana")
thisset = {"apple", "banana", "cherry"}
print(thisset)
thisset.add("orange")
print(thisset)
Note: If the item to remove does not exist, remove() will
thisset.update(["orange", "mango", "grapes"])
raise an error but discard() will NOT raise an error.
print(thisset)
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Change, Add & Remove from 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

Union of Two Sets Intersection of Two Sets


We can use this function to return all elements We can perform intersection operation in two ways:
present in both x and y sets 1. x.intersection(y) ==> by calling through intersection() method.
We can perform union operation in two ways: 2. x&y ==> by using '&' operator.
This operation returns common elements present in both sets x and y.
1. x.union(y) ==> by calling through union() method. x={10,20,30,40}
2. x|y ==> by using '|' operator. y={30,40,50,60}
This operation returns all elements present in both print(x.intersection(y)) #{40, 30}
sets x and y (without duplicate elements). print(x&y) #{40, 30}
x={10,20,30,40} Difference of Two Sets
y={30,40,50,60} We can perform difference operation in two ways:
print(x.union(y)) 1. x.difference(y) ==> by calling through difference() method.
#{10, 20, 30, 40, 50, 60} #Order is not preserved 2. x-y ==> by using '-' operator.
print(x|y) #{10, 20, 30, 40, 50, 60} This operation returns the elements present in x but not in y.
x={10,20,30,40}
OUTPUT: y={30,40,50,60}
{40, 10, 50, 20, 60, 30} print(x.difference(y)) #{10, 20}
{40, 10, 50, 20, 60, 30} print(x-y) #{10, 20}
print(y-x) #{50, 60}
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Dictionary
A dictionary is an unordered collection of elements in the form The generalized form of declaring a dictionary is:
of key : value pairs. d = {key1: value1, key2: value2, ... , keyn:valuen}
Let's consider an example:
Some of the examples where we use dictionaries to store key : month = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6}
value pairs are countries and capitals, cities and population, print(month)
goods and prices etc. # Result: {'Mar': 3, 'Feb': 2, 'Apr': 4, 'Jun': 6, 'Jan': 1, 'May': 5}
print(type(month)) # Result: <class 'dict'>
The keys of a dictionary should be unique and the values can A dict() function can also be used to construct a dictionary
change. So we use immutable data types(Number, string, tuple directly from a sequence of key-value pairs.
etc.) for the key and any type for the value. d = dict([('one', 1), ('two', 2), ('three', 3), ('four', 4)])
print(d) # Result: {'four': 4, 'three': 3, 'two': 2, 'one': 1}
➢ Unlike sequences which are indexed by a range of numbers,
print(d['four']) # Result: 4
dictionaries are indexed by keys.
Select all the correct statements from the given options:
➢ The elements of a dictionary are enclosed within { } braces. ❑ The keys in a dictionary are mutable.
➢ Tuples with same data type elements can be used as keys of ❑ The values of a dictionary should be immutable.
a dictionary. ❑ A dictionary is a collection of unordered elements and
➢ If any tuple contains a mutable object (such as a list) as an
each element will in the form a key: value pair.
element, the tuple cannot be used as a key. ❑ A tuple can be a key, if it only contain strings, numbers
➢ Usually a pair of braces { } represents an empty dictionary.
and lists.
➢ Elements can be added, modified or removed using the key. ❑ The dict() function is used to construct a dictionary.
Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Operation performed on Dictionary

The typical operations that can be performed on a dictionary are:


❖ Add elements i.e., key:value pairs.
❖ Access elements using the key with the index operator [ ] or using get() method.
❖ Update the value of a particular element given in the dictionary.
❖ The elements can also be deleted which results in deletion of both the key:value pair and we can also
delete the entire dictionary using del() method.
❖ Iterate through a dictionary for processing the elements in it.

Select all the correct statements from the given options:


❑ The elements in a dictionary can be either keys or values but not both.
❑ The indexing operator [] is used to access a key using the value as the parameter inside the indexing
operator.
❑ A value in a dictionary can be updated using the indexing operator along with the key.
❑ A for loop can be used to iterate through the elements of a dictionary.
❑ Deleting an element in a dictionary only deletes the value but not the key.

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

Deleting an element from a dictionary. Let's consider an example:


fruits = {1: 'apple', 2: 'orange', 3: 'mango', 4: 'grapes'}
❖ An element can be removed from the dictionary using print(type(fruits)) # Result: <type 'dict'>
the pop() method which takes a key as argument and print(fruits.pop(4)) #Result: grapes
returns the value associated. print(fruits) # Result: {1: 'apple', 2: 'orange', 3: 'mango'}
❖ If an invalid/non-existent key is provided with pop(), print(fruits.popitem()) # Result: (1, 'apple')
then a TypeError is shown. print(fruits) # Result: {2: 'orange', 3: 'mango'}
❖ The popitem() method can also be used to remove and del fruits[3]
it returns an arbitrary item (key, value) from the print(fruits) # Result: {2: 'orange'}
dictionary. fruits.clear()
❖ All the items can be removed from the dictionary using print(fruits) # Result: {}
the clear() method. This will make the dictionary empty del fruits
and doesn't delete the variable associated. print(fruits)
❖ The del keyword can be used to delete a single item or Traceback (most recent call last):
to delete the entire dictionary. File "<stdin>", line 1, in <module>
NameError: name 'fruits' is not defined

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Mutable Dictionary

As we observed that a dictionary is mutable: Create a dictionary using two lists.


❖ We can add new elements or modify existing ones using The zip() function in Python 3 creates pairs of elements
the assignment operator [ ]. from corresponding positions in multiple input
❖ To change a value, use the associated key with the sequences.
assignment operator. • It stops when the shortest input sequence is finished.
❖ If the key is already present in the dictionary, the • If given just one sequence, then it creates tuple pairs
associated value will be updated; otherwise, a new with single element in each tuple.
key:value pair will be added to the dictionary. list1 = [10, 20, 30]
result = zip(list1)
Let's consider an example: print(result) # Result: <zip object at 0x7ff536c7b1c8>
myset = set(result)
fruits = {1:'apple', 2:'orange', 3:'mango'} print(myset) # Result: {(10,), (30,), (20,)}
print(fruits) # Result: {1: 'apple', 2: 'orange', 3: 'mango'} • When no input is provided, it results in an empty
fruits[4] = 'grapes' outcome.
print(fruits) # Result: {1: 'apple', 2: 'orange', 3: 'mango', 4: list1 = []
'grapes'} result = zip(list1)
fruits[2] = 'guava' print(result) # Result: <zip object at 0x7ff536c7d7c8>
print(fruits) # Result: {1: 'apple', 2: 'guava', 3: 'mango', 4: mytuple = tuple(result)
'grapes'} print(mytuple) # Result: ()

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

The following table illustrates the dictionary methods.


Method Example Description
dict = {'cyan':1, 'violet':2, 'green':3}
Returns a list of (key,value) tuple
emp = {'Name': Anil, 'Age':26, 'Exp':5} items() print(dict.items()) # Result: [('cyan',
pairs
print(len(emp)) # Result: 3 Removes all elements 1), ('green', 3), ('violet', 2)]
clear()
emp.clear() print(len(emp)) # Result: from a dictionary.
dict = {'cyan':1, 'violet':2, 'green':3}
0 keys() print(dict.keys()) # Result: ['cyan',
Returns the keys of dictionary as a
list
'green', 'violet']
fruits = {'apple':'red',
'orange':'orange', 'mango':'yellow'}
Returns a shallow copy of dict1 = {'cyan':1, 'violet':2, 'green':3}
copy() dict2 = fruits.copy() print(dict2) # setdefault(ke dict1.setdefault('violet', 10) # Result: This method is similar to the
dictionary
Result: {'orange': 'orange', 'mango': y, default = 2 dict1.setdefault('red', 10) # Result: method get(). It will set dict[key] =
'yellow', 'apple': 'red'} None) 10 dict1 # Result: {'cyan': 1, 'violet': default, if key is not found
2, 'green': 3, 'red': 10}

Seq = ('one', 'two', 'three') dict = Creates a new dictionary


fromkeys(seq dict.fromkeys(Seq,10) print(dict) # using elements from dict1 = {'cyan':1, 'violet':2, 'green':3}
uence, value) Result: {'three': 10, 'two': 10, 'one': sequence as keys and dict2 = {'red':4, 'white':5} Appends one dictionary(dict2 in
update() dict1.update(dict2) print(dict1) # example) key:value pairs to the
10} values set to value Result: {'cyan': 1, 'violet': 2, 'green': calling dictionary(dict1 in example)
3, 'red': 4, 'white': 5}
dict = {'cyan':1, 'violet':2, 'green':3}
get(key, Returns a value for the
print(“Value : %s “ % dict.get('violet')) dict1 = {'cyan': 1, 'violet': 2, 'green':
default = key if found, else return
# Result: Value : 2 print((“Value: %s“ values() 3, 'red': 4} dict1.values() # Result: Returns a list of dictionary's values
None) the default which is None dict_values([1, 2, 3, 4])
%dict.get('red')) # Result: Value: None

Faculty Name: Dr. Subhash Chandra Gupta Programe Name: B.Tech (CSE)
Practice Questions

1. Write a Python script to sort (ascending and descending) a dictionary by value


2. Write a Python script to check if a given key already exists in a dictionary.
3. Write a Python script to merge two Python dictionaries
4. Write a Python program to add an item in a tuple.
5. Write a Python program to create a tuple with different data types
6. Write a Python program to sum all the items in a list
7. Write a Python program to get the largest number from a list.
8. Write a Python program to add member(s) in a set.
9. Write a Python program to reverse the order of the items in the array
10. Write a Python program to create an array of 5 integers and display the array items. Access individual
element through indexes.

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)

You might also like