You are on page 1of 141

Lists

A list can be created by putting the value inside the square bracket,
and values are separated by commas.

List_name = [value1, value2, …, value n]

Lists can contain any sort of object: numbers, strings, and even other
lists.

Lists Creation
Example 1:

1. shopping_list = ["jam", "milk", "bread", "butter"]

2. price_list = [13.99, 8.50, 7.90, 12.50]

3. mixed_list = ["Python", 100, 10.01, True, 'A']

Output:

print(shopping_list) # Output: ["jam", "milk", "bread", "butter"]

print(price_list) # Output: [13.99, 8.50, 7.90, 12.50]

print(mixed_list) # Output: ["Python", 100, 10.01, True, 'A']

Accessing Items Within Python Lists


print(shopping_list[0])
print(price_list [2])
print(mixed_list [-3])
Example 2:

num_list = [21, 13, 17, 39, 17, 51]

print(num_list[-1])

print(num_list[0])

print(num_list[-6])

print("The length of the list is {}.".format(len(num_list)))

Changing Values in Lists


num_list = [21, 13, 17, 39, 17, 51]

print(num_list)

num_list[4] = 33

print(num_list)

Creating a List of Lists

In Python, we can store lists within another list (nested lists). The
following code that makes one list containing other lists and values
with different data types.

data = [["Python", 100], ["Java", 101], "Hello", True]

print(data)
Accessing Elements from Lists

print(data[1])

print(data[0][0])

inner_list = data[1]

print(inner_list[0])

Creating Multi-Dimensional Lists in Python

One-dimensional Lists in Python:

init_list = [0]*3

print(init_list)

Output:

[0, 0, 0]

Two-dimensional Lists in Python:

two_dim_list = [ [0]*3 ] *3

print(two_dim_list)
Output:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Three-dimensional Lists in Python:

two_dim_list = [[ [0]*3 ] *3]*3

print(two_dim_list)

Output:

[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],

[[0, 0, 0], [0, 0, 0], [0, 0, 0]],

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]

Slicing Lists

 Python allows us to create list subsets using slicing techniques.


 To create a list slice, we specify the index of the first and last
items.
 The items from the first index up to, but not including, the last
index are copied into the slice, and it's evident that the copying
doesn't modify the original list.

Slicing with a Starting Index

Omitting the ending index means that the slice contains the list
elements from the starting index to the end of the list.

num_list = [21, 13, 17, 39, 17, 51]

print(num_list[3:])
Slicing with an Ending Index

Omitting the starting index means that the slice contains the list
elements from the beginning of the list up to the ending index.

num_list = [21, 13, 17, 39, 17, 51]

print(num_list[:4])

Omitting both the starting and ending indices results in the


entire list

Omitting the starting and ending index means it will print all the
elements of the list.

num_list = [21, 13, 17, 39, 17, 51]

print(num_list[:])

Slicing with Steps

We can use a step to return items at specified intervals. The step is


optional — by default, it is 1. The following code returns every other
item of num_list.

num_list = [21, 13, 17, 39, 17, 51]


print(num_list[ : :2])

Reversing a List with Negative Step

We can reverse a list by specifying the step as -1. The following code
returns the num_list items in reverse order without giving the start
and end index.

num_list = [21, 13, 17, 39, 17, 51]

print(num_list[ : :-1])

With start and end negative index with negative step

print(num_list[ -1: -7 :-1])

print(num_list[ -1: -7 :-2])

Understanding Slicing of Lists:


List1= [21, 13, 17, 39, 17, 51]
print(list1[0]) accesses the first item of the list.
print(list1[-4]) accesses the fourth item from the of the list.
print(list1[2:]) accesses a list of items from third to last.
print(list1[:4]) accesses a list of items from first to fourth.
print(list1[2:4]) accesses a list of items from third to fourth.
print(list1[1::2]) accesses alternate items, starting from the second
item.
print(list1[:-2]) accesses a list of items from the beginning to a
predefined index.
print(list1[-6:-1]) accesses a list of items of a range using negative
indexing.

List Comprehension

Python List comprehension helps in constructing lists in a


completely natural and easy way.

Python List comprehensions are used for creating new lists from
other iterables like tuples, strings, arrays, lists, etc.

A list comprehension consists of brackets containing the expression,


which is executed for each element along with the for loop to iterate
over each element.

Syntax

Example 1:

newList = [ expression(element) for element in oldList if condition ]

List1 = [ i for i in range(5)]

print(List1)

Output: [0, 1, 2, 3, 4]
Example 2:

Create a list that contains square of all odd numbers from range 1 to
10.

Program:

square_odd = [x ** 2 for x in range (1, 11) if x%2!=0]

print (square_odd)

Traditional Approach for the Above Code

square_odd = []

for x in range (1, 11):

if x%2!=0:

square_odd.append(x**2)

print (square_odd)

Example 3:

print ([a+b for a in ‘mug’ for b in ‘lid’])

Output: ['ml', 'mi', 'md', 'ul', 'ui', 'ud', 'gl', 'gi', 'gd']

Example 4:

list_fruit = ["Apple","Mango","Banana","Avocado"]

first_letters = [ fruits[0] for fruits in list_fruit]

print(first_letters)

Output: ['A', 'M', 'B', 'A']


Example 5: Print the prower of 2 from 1 to 8

power_of_2 = [2 ** x for x in range(1, 9)]

print (power_of_2)

Example 6:

#range 1 to 10

List1=[x**2 if x%2==1 else x*2 for x in range(1,11)]

print(list1)

Example 7: list for lowering the characters

print ([x.lower() for x in ["A","B","C"]] )

Example 8: list which extracts number

string = "my phone number is : 9648807086 !!"

print("\nExtracted digits")

numbers = [x for x in string if x.isdigit()]

print (numbers)

Example 9:

# A list of list for multiplication table


a=5
table = [[a, b, a * b] for b in range(1, 11)]

print("\nMultiplication Table")
for i in table:
print (i)
Add Elements in a List

There are two methods for adding new items into a list,
insert() and append() methods. The new item can be a
string, a number, or even another list. We can use both
methods to expand a list.

.insert()

The insert() method adds an item at a specified location


within a list.

fruits = ["apple", "orange", "cherry"]

fruits.insert(1, "pineapple")

print(fruits)

Output: ['apple', 'pineapple', 'orange', 'cherry']

.append()

The append() method adds an item at the end of a list.

fruits = ["apple","orange","cherry"]

fruits.append("pineapple")

print(fruits)
Output: ['apple', 'orange', 'cherry', pineapple']

Note:

You can add a list of objects at the end of a list with +=


operator. If the left operand of += is a list, the right operand
must be a list or any other iterable object.

students = ["xyz", "abc","def"]

students += ["zyx"]

students += ["hij", "klm"]

print(students)

Output: ['xyz', 'abc', 'def', 'zyx', 'hij', 'klm']

+ Operator

classA = ["xyz", "abc"]

classB = ["zyx", "cba"]

students = classA + classB

print(students)

Output: ["xyz", "abc", "zyx", "cba"]


extend()

We use the extend() method to add all the items of an


iterable (list, tuple, string, dictionary, etc.) to the end of the
list.
numbers = [1, 3, 5]

even_numbers = [4, 6, 8]

# add elements of even_numbers to the numbers list

numbers.extend(even_numbers)

print("List after append:", numbers)

Output: List after append: [1, 3, 5, 4, 6, 8]

Change List Items

In list we can change the items by assigning new values


using the = operator.
languages = ['Python', 'Swift', 'C++']
# changing the third item to 'C'
languages[2] = 'C'
print(languages)
Output: ['Python', 'Swift', 'C']

Reversing a List

Method 1: A list can be reversed by using the reverse()


method in Python.

mylist = [1, 2, 3, 4, 5, 'Java', 'Python']; mylist.reverse();


print(mylist)

Output: ['Python', 'Java', 5, 4, 3, 2, 1]

Method 2: Using the reversed() function

The reversed() function returns a reverse iterator, which can


be converted to a list using the list() function.

my_list = [1, 2, 3, 4, 5]

reversed_list = list(reversed(my_list))

print(reversed_list)

Output: [5, 4, 3, 2, 1]
Removing Items from a List

Method 1: remove() method

 The remove() method removes the first occurrence of


an element with a specified value.
 Error arises if the element doesn’t exist in the list.
 Remove() method only removes one element at a time,
to remove a range of elements, the iterator is used.
 The remove() method removes the specified item.
Example:
# Creating a list

list1 = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(list1)
# Removing elements from List
list1.remove(5)
list1.remove(6)
print("\nList after Removal of two elements: ")
print(List)

Output:
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List after Removal of two elements:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
Example 2:
# Creating a List
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
# Removing elements from List
# using iterator method
for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)
Output:
List after Removing a range of elements:
[5, 6, 7, 8, 9, 10, 11, 12]
Method 2: Using pop()
Syntax: list_name.pop(index)
 index (optional) – The value at index is popped out and removed.
If the index is not given, then the last element is popped out and
removed.
Return: Returns The last value or the given index value from the list.

Example 1: Without index

l = [1, 2, 3, 4]

print("Popped element:", l.pop())

print("List after pop():", l)

Output:
Popped element: 4
List after pop(): [1, 2, 3]
Example 2: With index

list1 = [1, 2, 3, 4, 5, 6]

# Pops and removes the 3th index

# element from the list

print(list1.pop(3), list1)

Output: 4 [1, 2, 3, 5, 6]

Example 2: Remove item with negative index


list1 = [1, 2, 3, 4, 5, 6]

poped_item = list1.pop(-2)

print("New list", list1)

print("Poped Item", poped_item)

Output:
New list [1, 2, 3, 4, 6]
Poped Item 5

Method 3: Using del statement


we can use the del statement to remove one or more items
from a list.
Example 1:
languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']
# deleting the second item
del languages[1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust', 'R']
# deleting the last item
del languages[-1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust']
# delete the first two items
del languages[0 : 2] # ['C', 'Java', 'Rust']
print(languages)

Remove duplicates from lists


Remove duplicate items from the list where some items are
repeated.
Example:
mylist = ["a", "b", "c", "d", "c"]
mylist = list(dict.fromkeys(mylist))
print (mylist)
Output: ['a', 'b', 'c', 'd']
The in and not in Operators
The in operator checks whether a specified value is in a list or not.
When the in operator is used in a condition, the statement returns a
Boolean value evaluating into either True or False.

When the specified value is found inside the list, the statement
returns True; otherwise, it returns False.

Example 1:

num_list = []
if not num_list:

print(“The list is empty.”)

Example 2:

languages = ['Python', 'Swift', 'C++']

if 'swift' in languages:

print ("it is available")

else:

print ("it is not available")

Example 3:

languages = ['Python', 'Swift', 'C++']

print('C' in languages) # False

print('Python' in languages) # True

List Methods

Methods Description
Append() Add an element to the end of the list
Extend() Add all elements of a list to another list
Insert() Insert an item at the defined index
Remove() Removes an item from the list
Clear() Removes all items from the list

list1 = [2, 1, 3, 5]; list1.clear();print(list1)#[]


Index() Returns the index of the first matched item
Syntax: list_name. index(element, start, end)

list1 = ['cat', 'bat', 'mat', 'cat', 'pet']


print(list1.index('bat')) # 1
Count() Returns the count of the number of items passed
as an argument

Syntax: list_name.count(object)

list1 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b']


print(list1.count('b')) # 3

list1 = [ ('Cat', 'Bat'), ('Sat', 'Cat'), ('Cat', 'Bat'),


('Cat', 'Bat', 'Sat'), [1, 2], [1, 2, 3], [1, 2] ]

print(list1.count(('Cat', 'Bat')))
print(list1.count([1, 2]))

list1 = [1, 1, 1, 2, 3, 2, 1]
print(list1.count(1, 2)) #Error
Sort() Sort items in a list in ascending order

#Ascending Order
unsorted_list = [2,4,5,32,6,255,5,42]
unsorted_list.sort()
print("Now it is sorted:", unsorted_list)

#Decending Order
numbers = [1, 3, 4, 2]
numbers.sort(reverse=True)
print(numbers)
reverse() Reverse the order of items in the list

list1 = [2, 1, 3, 5, 3, 8]
list1.reverse()
print(list1) # [8, 3, 5, 3, 1, 2]
copy() Returns a copy of the list

lis = [10, 20, 30]


new_list = lis.copy()
print('Copied List:', new_list)
pop() Removes and returns the item at the specified
index. If no index is provided, it removes and
returns the last item.

Built-in functions with List

Function Description
sum() Sums up the numbers in the list

Syntax: sum(iterable, start)

Iterable: list, tuple, or dictionary

numbers = [1,2,3,4,5,1,4,5]
Sum = sum(numbers)
print(Sum)
Sum = sum(numbers, 20)
print(Sum)
max() return maximum element of a given list

Syntax: max(arg1, arg2, *args[, key])

key : function where comparison of iterable


is performed based on its return value

Example 1:
var1 = 4
var2 = 8
var3 = 2
max_val = max(var1, var2, var3)
print(max_val) # 8

Example 2:
var1 = "Hello"
var2 = "Hi"
var3 = "Hru"
max_val = max(var1, var2, var3, key=len)
print(max_val)

Example 3:
list = [1.2, 1.3, 0.1]
max_value = max(list)
print(max_value)
min() return minimum element of a given list

var1 = 4
var2 = 8
var3 = 2
max_val = min(var1, var2, var3)
print(max_val) # 8

all() Returns true if all element is true or if the list


is empty

any() return true if any element of the list is true. if


the list is empty, return false

# Since all are false, false is returned


print (any([False, False, False, False]))
# second item (True) and will return True.
print (any([False, True, False, False]))

# first (True) and will return True.


print (any([True, False, False, False]))
len() Returns length of the list or size of the list

string1 = "PPSclass"
# printing length of string1
print(len(string1)) # 8
map() returns a list of the results after applying the
given function to each item of a given
iterable

Syntax: map(fun, iter)

Example 1:
def addition(n):
return n + n

numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
Example 2:
# List of strings
l = ['sat', 'bat', 'cat', 'mat']
# map() can listify the list of strings
individually
test = list(map(list, l))
print(test)
Output: [['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'],
['m', 'a', 't']]
filter() tests if each element of a list is true or not

# function that filters vowels


def fun(variable):
letters = ['a', 'e', 'i', 'o', 'u']
if (variable in letters):
return True
else:
return False

# sequence
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']

# using filter function


filtered = filter(fun, sequence)

print('The filtered letters are:')


for s in filtered:
print(s)

Output:

The filtered letters are:


e
e
Tuple
When working with data collections, we occasionally encounter
situations where we want to ensure it's impossible to change the
sequence of objects after creation.

Python has a built-in sequence data type to store data in an


unchangeable object, called a tuple.

A tuple represents a sequence of any objects separated by


commas and enclosed in parentheses.

A tuple is an immutable object, which means it cannot be changed,


and we use it to represent fixed collections of items.

Key Points of Tuple

KEY POINTS EXPLANATION


OF TUPLE
Immutable Once a tuple is created, its elements cannot be
modified.
Ordered A tuple is an ordered collection of items,
Collection meaning the items are stored in a specific order
and can be accessed by their index.
Parenthesis A tuple is represented by a sequence of values
separated by commas, enclosed in parentheses.
Memory Tuples are stored in a single block of memory,
Efficient which makes them more memory efficient than
lists.
Built-in Tuples have several built-in methods that can
KEY POINTS EXPLANATION
OF TUPLE
Methods be used for common operations like counting
the number of occurrences of an element,
finding the index of an element, etc.
Tuple Tuples can be used for multiple assignments in
Unpacking a single line, which is known as tuple
unpacking.
Use as Key in Tuples can be used as keys in a dictionary,
Dictionary which uses the hash value of the key to retrieve
the corresponding value.

Some examples of Python tuples

 () — an empty tuple
 (1.0, 9.9, 10) — a tuple containing three numeric objects
 ("apple", "banana", "mango") — a tuple containing four string
objects
 ('10', 101, True) — a tuple containing a string, an integer, and a
Boolean object

Create a Tuple in Python


There are several different ways to create a tuple in Python.
The most common is to use round brackets () to enclose a comma-
separated list of elements.
tuple() – Create a Tuple
 The tuple() constructor is a built-in Python function that
creates a tuple from an iterable.
 An iterable is any Python object that can be looped over, such
as a list, string, or range.
 When the tuple() constructor is called with an iterable, it
returns a new tuple containing the items from the iterable.
An empty tuple, using the “tuple()” constructor with no
arguments:
# Create tupe using constructor
my_tuple = tuple()
data_type = print(type(my_tuple)) # output: < class 'tuple' >

A tuple with items, using the “tuple()” constructor with the


items as arguments:
# Creat tuple by taking list as argument
my_tuple = tuple([1, 2, 3])
print(my_tuple) # output: (1, 2, 3)

my_tuple = tuple("pps")
print (my_tuple) # output: ('p', 'p', 's')

Note: The tuple() constructor takes one optional argument. The


arguments must be iterable, like a list or a string.
Tuple Creation Using Round Parentheses
To create a tuple using round parentheses, you simply enclose a
comma-separated list of elements inside round brackets.
For example, the following creates a tuple with three elements:
Example 1:
my_tuple = (1, 2, 3)
print (my_tuple) #output: (1, 2, 3)

Example 2:
a=1;b=2;c=3
my_tuple = (a, b, c)
print (my_tuple) #output: (1, 2, 3)

Example 3: Empty tuple


my_tuple = ()
print (type (my_tuple)) # <class 'tuple'>

Tuple with Single Element


In case you are generating a tuple with a single element, make
sure to add a comma after the element.
Example:
my_tuple = ("PPS",)
print(type(my_tuple)) #output: <class 'tuple'>
#NOT a tuple
my_tuple = ("PPS")
print(type(my_tuple)) #output: <class 'str'>
The trailing comma means that the parentheses are holding a
single-value tuple.

Create a Nested Tuple


A nested tuple is a tuple that contains one or more tuples as its
elements.
To create a nested tuple, you can include a tuple as an element
within another tuple.
Example 1
my_tuple = (1, ("python", "java"))
Example 2
my_tuple = (1, (2, (3, 4)))
Example 3
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'Java')
tuple3 = (tuple1, tuple2)
print(tuple3) #Output: ((0, 1, 2, 3), ('python', 'Java'))

Also, other objects like lists and tuples can comprise a tuple,
like this:
a_tuple = (0, [1, 2, 3], (4, 5, 6), 7.0)
print(a_tuple) # output: (0, [1, 2, 3], (4, 5, 6), 7.0)
print(type(a_tuple)) # type: <class 'tuple'>

Accessing Elements from Tuple


Accessing elements in a tuple is similar to accessing elements in a
list. You can use the index of an element to access it.
The index of the first element is 0, the index of the second
element is 1, and so on.
You can also use negative indexing to access elements from the end
of the tuple.
# Create tuple
Example 1:
my_tuple = ('Python', 'Java', 'C++', 'JavaScript')
# Access tuple element
first_language = my_tuple[0]
print(first_language) # Output: 'Python'

last_language = my_tuple[-1]
print(last_language) # Output: 'JavaScript'

Example 2:
a_tuple = (0, [1, 2, 3], (4, 5, 6), 7.0)
print('The first element:', a_tuple[0])
print('The second last element:', a_tuple[-2])
Find the second element of the inner tuple, at index 2.
print(a_tuple[2][1]) # Output: 5
Slicing to Access a Range of Elements
Use slicing to access a range of elements in a tuple.
# Slice tuple
my_tuple = ('Python', 'Java', 'C++', 'JavaScript')
first_two_languages = my_tuple[:2]
print(first_two_languages)

num_tuple = 2, 4, 5, 7, 8, 10
print(num_tuple[:3])
print(num_tuple[4:])
print(num_tuple[-3:])
print(num_tuple[2:5])

Output:
(2, 4, 5)
(8, 10)
(7, 8, 10)
(5, 7, 8)
Access the Elements of a Nested Tuples
To access the elements of a nested tuple, you can use multiple
indices to access elements at different levels of nesting. It is the
same as accessing the element of the nested list.
# Creates a nested tuple with elements
my_tuple = ('Python', ('Java', 'C++'), ('JavaScript', ('Scala', 'Kotlin')))

# Accesses the first element of the tuple


first_element = my_tuple[0]

# Accesses the first element of the second tuple


second_element = my_tuple[1][0]

# Accesses the first element of the third tuple


third_element = my_tuple[2][1][0]

Different Data Types Allowed in a Tuple


A tuple can contain an integer, a string, a list, a float, or any
other datatype. There is no restriction on elements inside a
Tuple in Python.

Example 1: Tuple with integers and strings


my_tuple = (1, 2, 3, 'hello', 'world')
Example 2: Tuple with a mix of data types
my_tuple = (1, 'hello', [1, 2, 3], 3.14, (1, 2))
Example 3: Tuple with a boolean and None
my_tuple = (True, None)
Example 4: Tuple with a set and a dictionary
my_tuple = ({"name": "Alex", "age": 25}, {1, 2, 3})

Concatenate two or more tuples


tuple_1 = (1, 2)
tuple_2 = (3, 4)
print(tuple_1 + tuple_2) # Output: (1, 2, 3, 4)

Multiplying a tuple
Multiplying a tuple by an integer produces a tuple containing the
original tuple repeated that many times.
my_tuple = (1, 7, 9, 8)
print(my_tuple * 2) # Output: (1, 7, 9, 8, 1, 7, 9, 8)

Perform for Loop on a Tuple


You can use a for loop to iterate over the elements of a tuple in
Python. This is same as if you are iterating over other iterable, like
list, set, or range.
# Syntax
for element in iterable:
# write code here

# Example of tuple with for loop


my_tuple = ('Python', 'Java', 'C++', 'JavaScript')
for element in my_tuple:
print(element)

enumerate() and FOR Loop on a Tuple


Use the enumerate() function in combination with a for loop to
iterate over the elements of a tuple in Python while also keeping
track of the index of each element.
# Using enum
for index, element in enumerate(my_tuple):
print(index, element)
Output:
0 Python
1 Java
2 C++
3 JavaScript
Deleting a Tuple in Python
Removing individual tuple elements is not possible, but we can
delete the whole Tuple using Del keyword.
Tuple1 = (0, 1)

del tuple1
print(tuple1)

Finding the Length of a Python Tuple


tuple2 = ('python', 'Java')
print(len(tuple2))

Converting a List and Stringto a Tuple


We can convert a list in Python to a tuple by using the tuple()
constructor and passing the list as its parameters.
list1 = [0, 1, 2]
print(tuple(list1))
# string 'python'
print(tuple('python'))

Remove and Add Elements to Tuple


As a Python tuple is an immutable data structure, you cannot add or
remove elements from an existing tuple.
If you need to add or remove elements, you will have to create a new
tuple with the desired elements.
Adding an element to a tuple can be done by concatenating the new
element with the existing tuple using the + operator, or by using the
tuple() function to convert a list with the new elements into a
tuple.
my_tuple = ('Python', 'Java', 'C++', 'JavaScript')
# Add element using + operator
new_tuple = my_tuple + ("Swift",)
# Output: ('Python', 'Java', 'C++', 'JavaScript', 'Swift')
print(new_tuple)
# Remove Elements using Slicing
new_tuple = my_tuple[:2] + my_tuple[3:]
print (new_tuple)
# Output: ('Python', 'Java', 'JavaScript')

Using Tuples as a Return Value


With tuples, you can return multiple values from a function.
Functions in Python can only return one value, but sometimes it is
useful to return multiple values.
# Create function that returns muliple values
def divide(a, b):
if b == 0:
return (False, "Cannot divide by zero")
else:
return (True, a / b)
success, result = divide(5, 2)
if success:
print(result)
else:
print(result)
Unpacking Values

Unpacking a tuple allows us to extract the tuple elements and assign


them to named variables.

Example 1

my_tuple = (1, 'hello', [1, 2, 3])


a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 'hello'
print(c) # Output: [1, 2, 3]

Difference Between Tuples and Lists in Python

Lists more preferable iterable objects than tuples are that a list
object provides more methods.

But lists occupy more space than tuples, i.e., list object occupies
more memory than a tuple object.

import sys
a_list = ['abc', 'xyz', 123, 231, 13.31, 0.1312]
a_tuple = ('abc', 'xyz', 123, 231, 13.31, 0.1312)
print('The list size:', sys.getsizeof(a_list), 'bytes')
print('The tuple size:', sys.getsizeof(a_tuple), 'bytes')
Tuple Element Swapping
x = 19
y = 91
print('Before swapping:')
print(f'x = {x}, y = {y}')
(x, y) = (y, x)
print('After swapping:')
print(f'x = {x}, y = {y}')

Tuple Functions

The count() Function

This function will help us to fund the number of times an element is


present in the tuple.

tup = (22, 45, 23, 78, 22, 22, 6.89)

print(tup.count(22)) #Output: 3

The index() Function

The tuple index() method helps us to find the index or occurrence of


an element in a tuple. This function basically performs two
functions:

 Giving the first occurrence of an element in the tuple.


 Raising an exception if the element mentioned is not found in the
tuple.

Example 1: Finding the index of an element


tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)
print(tup.index(45)) # Output: 2

print(tup.index(3.2)) # Output: ValueError: tuple.index(x): x not in


tuple.

The sorted() Function

This method takes a tuple as an input and returns a sorted list as an


output. Moreover, it does not make any changes to the original tuple.

tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

sorted(tup) # Output: [1, 2, 2.4, 3, 4, 22, 45, 56, 890]

The min(), max(), and sum() Tuple Functions

min(): gives the smallest element in the tuple as an output. Hence,


the name is min().

max(): gives the largest element in the tuple as an output. Hence,


the name is max().

tup = (22, 3, 45, 4, 2.4, 2, 56, 890, 1)

min(tup) # Output: 1

max(tup) # Output: 890

sum(): gives the sum of the elements present in the tuple as an


output.
sum(tup) # Output: 1023

The all() function

Returns true if all element is true or if tuple is empty

print(all((True, True, False))) # Output: False

t = (4, 5, 1)
print(all(t)) # Output: True

t = (5, 0, 3, 1, False)
print(all(t)) # Output: False

t = ()
print(all(t)) Output: True

The any() function

Return true if any element of the tuple is true. if tuple is empty,


return false.

t = (False, False, True, False, False)


print(any(t)) # Output: True

t = (4, 5, 1)
print(any(t)) # Output: True

t = (0, 0, False)
print(any(t)) # Output: False
t = ()
print(any(t)) # Output: False

Tuples VS Lists:

Similarities Differences

Functions that can be


used for both lists and
Methods that cannot be used for tuples:
tuples:
append(), insert(), remove(), pop(), clear(),
len(), max(), min(),
sort(), reverse()
sum(), any(), all(),
sorted()

Methods that can be used we generally use ‘tuples’ for heterogeneous


for both lists and tuples: (different) data types and ‘lists’ for
count(), Index() homogeneous (similar) data types.

Tuples can be stored in


Iterating through a ‘tuple’ is faster than in a ‘list’.
lists.

Lists can be stored in ‘Lists’ are mutable whereas ‘tuples’ are


tuples. immutable.

Both ‘tuples’ and ‘lists’ Tuples that contain immutable elements can be
can be nested. used as a key for a dictionary.
Set
A set is a built-in Python data structure used to store a collection of
unique items, potentially of mixed data types, in a single variable.

Python sets are:

Unordered – the items of a set don’t have any defined order. This
means that they do not preserve the original order in which they
were created.

Example:

>>> x = {'a','b','c'}

>>> print(x)

>>> x

{'a', 'c', 'b'}

Unindexed – we can't access the items with index as with lists.

Example:

>>> x = {'a','b','c'}

>>> print(x[0])

TypeError: 'set' object is not subscriptable

Mutable – They can be changed once a Set has been created.

Unchangeable – Set items are unchangeable, but you can remove


items and add new items.

>>> x{0} = 'y'


SyntaxError: cannot assign to function call

Iterable – we can loop over the items of a set.

Cannot contain duplicate values: Set elements must be unique, as


duplicates are not allowed. In case a duplicate value is added, it will
be displayed only once.

Example:

>>> x = {'a','b','c','c'}

>>> print(x)

{'a', 'c', 'b'}

Note:

Python set itself is mutable (we can remove items from it or add
new ones), but its items must be immutable data types, like integers,
floats, tuples, or strings.

Creating a Python Set

We can create a Python set in two ways:

1. By using the built-in set() function with an iterable object


passed in (such as a list, tuple, or string).
2. By placing all the items separated by a comma inside a pair of
curly braces {}.

The set() function

set1 = set([1, 1, 1, 2, 2, 3]) # from a list

set2 = set(('a', 'a', 'b', 'b', 'c')) # from a tuple

set3 = set('anaconda') # from a string


print('Set1:', set1) # Output: Set1: {1, 2, 3}

print('Set2:', set2) # Output: Set2: {'b', 'c', 'a'}

print('Set3:', set3) # Output: {'n', 'o', 'd', 'c', 'a'}

Using curly braces {}

set4 = {1, 1, 'pps', 'pps', 8.6, (1, 2, 3), None} # mixed datatypes

print('Set4:', set4) # Output: {1, 8.6, 'pps', (1, 2, 3), None}

Creating a Set by including lists and dictionaries

We cannot include lists and dictionaries in sets as they are


mutable.

>>> lis = ['This', 'is', 'a', 'list']

>>> {lis} # Output: TypeError: unhashable type: 'list'

>>> dictionary = {'month': 1, 'day': 12}

>>> {dictionary} # Output: TypeError: unhashable type: 'dict'

# creating a set with mutable items

set5 = {1, 1, ' pps', 'pps', 8.6, [1, 2, 3], {1, 2, 3}}

print('Set5:', set5)

Output: TypeError: unhashable type: 'list'

We can make the following observations here:

 The duplicates have been removed from the sequence in each


case
 The initial order of the items has changed
 set4 contains elements of different data types
 An attempt to create a Python set with mutable items (a list
and a set) resulted in a TypeError

Creating set using <iterable> can be any iterable object such as


a list, string, or tuple

Passing list as an iterable:

sample_set = set(['100', 'Days', 'Of', 'Code'])

print(sample_set) # Output: {'Of', '100', 'Days', 'Code'}

Passing tuple as an iterable:

sample_set = set(('Tuple', 'as', 'an', 'iterable'))

print(sample_set) # Output: {'as', 'iterable', 'an', 'Tuple'}

Passing string as an iterable:

s = set('Alpha')

print(s) # Output: {'p', 'l', 'a', 'h', 'A'}

Creating Empty Python set:

Empty curly braces {} create an empty Python dictionary, we can’t


use this approach to create an empty set in Python.

Using the set() function is still valid in this case.

empty1 = {}

empty2 = set()

print(type(empty1)) # <class 'dict'>


print(type(empty2)) # <class 'set'>

Examples of set creation:

# create a set of integer type

student_id = {112, 114, 116, 118, 115}

print('Student ID:', student_id)

# Output: Student ID: {112, 114, 115, 116, 118}

# create a set of string type

vowel_letters = {'a', 'e', 'i', 'o', 'u'}

print('Vowel Letters:', vowel_letters)

# Output: Vowel Letters: {'u', 'a', 'e', 'i', 'o'}

# create a set of mixed data types

mixed_set = {'Hello', 101, -2, 'Bye'}

print('Set of mixed data types:', mixed_set)

# Output: Set of mixed data types: {'Hello', 'Bye', 101, -2}

Type Casting and adding element to the set

myset = set(["a", "b", "c"])

print(myset) # Output: {'c', 'b', 'a'}

# Adding element to the set

myset.add("d")
print(myset) # Output: {'d', 'c', 'b', 'a'}

Set Membership

To check whether a certain item is present or not in a Python set, we


use the operator keywords in or a combination of keywords not in:

>>> myset = {1, 2, 3}

>>> print(1 in myset)

True

>>> print(1 not in myset)

False

>>> sample_set = set(['100', 'Days', 'Of', 'Code'])

>>> '100' in sample_set

True

>>> '100' not in sample_set

False

>>> 'red' in sample_set

False

Accessing Values in a Python Set

Since a Python set is unordered and unindexed, we can't access its


items by indexing or slicing. One way to do so is by looping through
the set:
myset = {'a', 'b', 'c', 'd'}

for item in myset:

print(item)

Note: The order of the output values can differ from the succession
shown in the original set.

Modifying a Python Set

Adding Items to a Python Set

The add() method

Add a single immutable item to a Python set

The update() method

 Several immutable items.


 It takes tuples, lists, strings, or other sets of immutable items as
its argument and then adds each single unique item from them
(or each single unique character, in the case of strings) to the
set:

# Initial set

myset = set()

# Adding a single immutable item

myset.add('a')

print(myset) # Output: {'a'}

# Adding several items


myset.update({'b', 'c'}) # a set of immutable items

print(myset) # Output: {'b', 'c', 'a'}

myset.update(['d', 'd', 'd']) # a list of items

print(myset) # Output: {'b', 'd', 'c', 'a'}

myset.update(['e'], ['f']) # several lists of items

print(myset) # Output: {'e', 'f', 'b', 'd', 'c', 'a'}

myset.update('fgh') # a string

print(myset) # Output: {'e', 'f', 'b', 'h', 'd', 'c', 'a', 'g'}

myset.update([[1, 2], [3, 4]]) # an attempt to add a list of mutable


items (lists)

print(myset) # Output: TypeError: unhashable type: 'list'

Removing Items from a Python Set

To remove an item/items from a Python set, we can opt for one of


four methods:

1. discard() – removes a particular item or does nothing if that


item is absent in the set
2. remove() – removes a particular item or raises KeyError if that
item is absent in the set
3. pop() – removes and returns a random item or
raises KeyError if the set is empty
4. clear() – clears the set (removes all the items)

# Initial set
myset = {1, 2, 3, 4}

print(myset) # Output: {1, 2, 3, 4}

# Removing a particular item using the discard() method

myset.discard(1) # the item was present in the set

print(myset) # Output: {2, 3, 4}

myset.discard(5) # the item was absent in the set

print(myset) # Output: {2, 3, 4}

# Removing a particular item using the remove() method

myset.remove(4) # the item was present in the set

print(myset) # Output: {2, 3}

myset.remove(5) # the item was absent in the set

print(myset) # Output: KeyError: 5

# Taking the set from the code above

myset = {2, 3}

# Removing and returning a random item

print(myset.pop()) # the removed and returned item: Output: 2

print(myset) # The updated set: Output: {3}

# Removing all the items

myset.clear()
print(myset) # empty set Output: set()

# An attempt to remove and return a random item from an empty


set:

myset.pop()

print(myset) # Output: KeyError: 'pop from an empty set'

Built-in Python Functions for Sets

 len() – returns the set size (the number of items in the set).
 min() and max() – return the smallest/largest item in the set and
are mostly used for the sets with numeric values.
 sum() – returns the sum of all items of the set containing only
numeric values.

# A set with numeric items

myset = {5, 10, 15}

print('Set:', myset) # Set: {10, 5, 15}

print('Size:', len(myset)) # Size: 3

print('Min:', min(myset)) # Min: 5

print('Max:', max(myset)) # Max: 15

print('Sum:', sum(myset)) # Sum: 30

print('\n')
# A set with string items

myset = {'a', 'A', 'b', 'B'}

print('Set:', myset) # Set: {'A', 'b', 'a', 'B'}

print('Min:', min(myset)) # Min: A

print('Max:', max(myset)) # Max: b

print('\n')

# A set with tuple items

myset = {(1, 2), (1, 0), (2, 3)}

print('Set:', myset) # Set: {(1, 0), (1, 2), (2, 3)}

print('Min:', min(myset)) # Min: (1, 0)

print('Max:', max(myset)) # Max: (2, 3)

 all() – returns True if all items of the set evaluate to True, or if the
set is empty.

print(all({1, 2})) # True

print(all({1, False})) # False

 any() – returns True if at least one item of the set evaluates


to True (for an empty set, returns False).

print(any({1, False})) # True

print(any({False, False})) # False


 sorted() – returns a sorted list of items of the set.

myset = {4, 2, 5, 1, 3}

print(sorted(myset)) # [1, 2, 3, 4, 5]

myset = {'c', 'b', 'e', 'a', 'd'}

print(sorted(myset)) # ['a', 'b', 'c', 'd', 'e']

Mathematical Set Operations on Python Sets

This group of operations includes union, intersection, difference,


and symmetric difference.

Mathematical set operations on the following two Python sets:

a = {1, 2, 3, 4, 5}

b = {4, 5, 6, 7}

Set Union

The union of two (or more) Python sets returns a new set of all the
unique items from both (all) sets. It can be performed using the |
operator or the union() method:

print(a | b) # {1, 2, 3, 4, 5, 6, 7}

print(b | a) # {1, 2, 3, 4, 5, 6, 7}

print(a.union(b)) # {1, 2, 3, 4, 5, 6, 7}

print(b.union(a)) # {1, 2, 3, 4, 5, 6, 7}
As we can see, for the union operation, the order of sets doesn’t
matter: we can write a | b or b | a with the identical result, and the
same can be said about using the union() method.

The syntax for the union operation on more than two Python
sets is the following: a | b | c or a.union(b, c).

Set Intersection

The intersection of two (or more) Python sets returns a new set of
the items common to both (all) sets. It can be performed using the
& operator or the intersection() method:

a = {1, 2, 3, 4, 5}

b = {4, 5, 6, 7}

print(a & b) # {4, 5}

print(b & a) # {4, 5}

print(a.intersection(b)) # {4, 5}

print(b.intersection(a)) # {4, 5}

Again, in this case, the order of sets doesn’t matter: a & b or b & a
will yield the same result, and the same is true when using the
intersection() method.

The syntax for the intersection operation on more than two


Python sets is the following: a & b & c or a.intersection(b, c).

Set Difference

The difference of two (or more) Python sets returns a new set
containing all the items from the first (left) set that are absent in
the second (right) set.
In the case of more than two sets, the operation is performed from
left to right. For this set operation, we can use the - operator or
the difference() method:

a = {1, 2, 3, 4, 5}

b = {4, 5, 6, 7}

print(a - b) # {1, 2, 3}

print(b - a) # {6, 7}

print(a.difference(b)) # {1, 2, 3}

print(b.difference(a)) # {6, 7}

Here the order of sets matters: a - b (or a.difference(b)) returns


all the items that are in a but not in b, while b - a (or
b.difference(a)) returns all the items that are in b but not in a.

The syntax for the difference operation on more than two Python
sets is the following: a - b - c or a.difference(b, c). In such cases, we
first compute a - b, then find the difference between the resulting
set and the next one to the right, which is c, and so on.

Set Symmetric Difference

The symmetric difference of two Python sets returns a new set of


items present in either the first or second set, but not both.

In other words, the symmetric difference of two sets is the


difference between the set union and set intersection, and this
makes sense also for the symmetric difference of multiple sets. We
can perform this operation using the ^ operator or the
symmetric_difference() method:
a = {1, 2, 3, 4, 5}

b = {4, 5, 6, 7}

print(a ^ b) # {1, 2, 3, 6, 7}

print(b ^ a) # {1, 2, 3, 6, 7}

print(a.symmetric_difference(b)) # {1, 2, 3, 6, 7}

print(b.symmetric_difference(a)) # {1, 2, 3, 6, 7}

For the symmetric difference operation, the order of sets doesn’t


matter: a ^ b or b ^ a will yield the same result, and we can say the
same about using the symmetric_difference() method.

The syntax for the symmetric difference operation on more than


two Python sets is the following: a ^ b ^ c. However, this time, we
can't use the symmetric_difference() method since it takes
exactly one argument and otherwise raises TypeError:

a = {1, 2, 3, 4, 5}

b = {4, 5, 6, 7}

c = {7, 8, 9}

a.symmetric_difference(b, c)

TypeError: set.symmetric_difference() takes exactly one


argument (2 given)
Other Set Operations on Python Sets

There are several other useful methods and operators for working
with two or more Python sets:

intersection_update() (or the &= operator) — rewrites the


current set with the intersection of this set with another one (or
multiple sets)

Example:

# Performs intersection between A, B and C and updates the result


to set A

# Compare 3 sets, and return a set with items that is present in all 3
sets:

A = {1, 2, 3, 4}

B = {2, 3, 4, 5, 6}

C = {4, 5, 6, 9, 10}

A.intersection_update(B, C)

A &= B

A &= C

print ('A intersection_update (B, C): ', A)

print('A &= B: ', A)

print('A &= C: ', A)


difference_update() (or the -= operator) — rewrites the current
set with the difference of this set with another one (or multiple
sets).

# The difference_update() method computes the difference between


two sets (A - B) and updates set A with the resulting set.

# sets of numbers

A = {1, 3, 5, 7, 9}

B = {2, 3, 5, 7, 11}

# computes A - B and updates A with the resulting set

A.difference_update(B)

A -= B

print('A. difference_update(B): ', A) # Output: A = {1, 9}

print ('A -= B: ', A) # Output: A = {1, 9}

symmetric_difference_update() (or the ^= operator) — rewrites


the current set with the symmetric difference of this set with
another one (or multiple sets)

# The symmetric difference between the two sets is the set of


elements that are in either of the sets but not in both of them.

A = {"apple", "banana", "cherry"}

B = {"google", "microsoft", "apple"}

A. symmetric_difference_update(B)

A ^= B
print('A. symmetric_difference_update(B): ', A)

print ("A ^= B", A)

Output:

A. symmetric_difference_update(B): {'apple', 'cherry', 'banana'}

A ^= B {'apple', 'cherry', 'banana'}

isdisjoint() — returns True if two sets don’t have any items in


common, meaning that the intersection of these sets is an empty set.

# Return True if no items of one set is present in another set:

A = {1, 2, 3}

B = {4, 5, 6}

# checks if set A and set B are disjoint

print(A.isdisjoint(B)) # True

issubset() (or the <= operator) — returns True if another set


contains each item of the current set, including the case when both
sets are identical. If we want to exclude the latter case, we can’t use
this method; instead, we need to use the < (strictly smaller)
operator.

# Return True if all items in set x are present in set y:

A = {1, 2, 3}

B = {1, 2, 3, 4, 5}

# all items of A are present in B

A <= B
print (A <= B) # True

print (B <= A) # False

print(A.issubset(B)) # True

print(B.issubset(A)) # False

issuperset() (or the >= operator) — returns True if the current


set contains each item of another set including the case when both
sets are identical. If we want to exclude the latter case, we can’t use
this method; instead, we need to use the > (strictly greater)
operator.

# Return True if all elements of a set B are in set A. Then Set A is the
superset of set B.

A = {4, 1, 3, 5}

B = {6, 0, 4, 1, 5, 0, 3, 5}

print (A>=B) # False

print(B>=A) # True

print("A.issuperset(B) : ", A.issuperset(B)) # False

print("B.issuperset(A) : ", B.issuperset(A)) # True

Set Comprehension

Set comprehension is a method for creating sets in python using the


elements from other iterables like lists, sets, or tuples.

Syntax
Set comprehension has a simple and elegant syntax that consists of
two parts:

new_set = {expression for variable in iterable if condition}

new_set: the new set you want to create.

expression: an expression that defines the value of each element in


the new set.

variable: a variable that takes each value in the iterable object.

iterable: an iterable object, such as a list, a tuple, or a range, that


provides values for the variable.

condition (optional): a conditional statement that filters the


elements in the iterable object.

The for loop and the if statement are the two fundamental building
blocks of set comprehension.

The for loop iterates over the iterable object, and the if statement
filters the elements based on a condition.

Example 1:

Creating a new set of squared values

numbers = [1, 2, 3, 4, 5]

squared_numbers = {x**2 for x in numbers}

print(squared_numbers)

Output: {1, 4, 9, 16, 25}

Example 2:
Filtering elements in a list

numbers = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]

even_numbers = {x for x in numbers if x % 2 == 0}

print(even_numbers)

Output: {2, 4, 6}

Filtering elements without Set Comprehension

Example 3:

input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]

output_set = set()

for var in input_list:

if var % 2 == 0:

output_set.add(var)

print("Output Set using for loop:", output_set)

Output: Output Set using for loop: {2, 4, 6}

Using a set comprehension with strings

Create a new set called vowel_words that contains only the words
from the words list that contain at least one vowel.

Example

words = ['apple', 'banana', 'cherry', ]


vowels = {'a', 'e', 'i', 'o', 'u'}

vowel_words = {word for word in words if any(letter in vowels for


letter in word)}

print(vowel_words)

Output: {'cherry', 'banana', 'apple'}

Example 4:

Create a set of the triples of the given integers.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

newSet = {element*3 for element in myList}

print("The existing list is:")

print(myList)

print("The Newly Created set is:")

print(newSet)

Output:

The existing list is:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The Newly Created set is:

{3, 6, 9, 12, 15, 18, 21, 24, 27, 30}


Example 5:
Create a set of triples of even integers
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
newSet = {element*3 for element in myList if element % 2 ==0}
print("The existing list is:")
print(myList)
print("The Newly Created set is:")
print(newSet)
Output:
The existing list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The Newly Created set is:
{6, 12, 18, 24, 30}

Example 6:
Create a set from elements of another set
mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
newSet = {element ** 2 for element in mySet}
print("The Newly Created set is:")
print(newSet)
Output:
The Newly Created set is:
{64, 1, 4, 36, 100, 9, 16, 49, 81, 25}
Filter or Delete elements from a set
mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print("The existing set is:")
print(mySet)
mySet = {element for element in mySet if element % 2 == 0}
print("The modified set is:")
print(mySet)
Output:
The existing set is:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The modified set is:
{2, 4, 6, 8, 10}

Question: Create a set that hold elements that are less than and
greater than 6.

Change the data type of elements of the set


mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
newSet = {str(element) for element in mySet }
print("The existing set is:")
print(mySet)
print("The Newly Created set is:")
print(newSet)
Output:
The existing set is:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The Newly Created set is:
{'2', '4', '8', '6', '3', '7', '1', '10', '5', '9'}

Create Set from Tuple using Set Comprehension


myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
newSet = {element*2 for element in myTuple if element % 2 ==0}
print("The existing tuple is:")
print(myTuple)
print("The Newly Created set is:")
print(newSet)
Output:
The existing tuple is:
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
The Newly Created set is:
{4, 8, 12, 16, 20}

Key Takeaways
 Set comprehension may be a concise and effective way to form
a new set based on an existing iterable object, such as a list or a
tuple.
 The syntax for set comprehension comprises two parts: a new
set and an expression that defines the value of each element
within the set.
 It can incorporate a variable that takes each value within the
iterable object and a conditional statement that filters the
elements.
 Best practices include keeping it basic, utilizing significant
variable names, and utilizing curly braces to extend
meaningfulness.
 Set comprehension may be a capable and exquisite highlight of
Python that can assist you in writing more brief and readable
code and spare you time and exertion.

Quiz
1. What is set comprehension in Python?
 A way to create a new set based on an existing iterable object
 A way to convert a list into a set
 A way to modify an existing set
 A way to create a new list
2. Which of the following is the syntax for set comprehension?
 new_set = {expression for variable in iterable if condition}
 new_set = {expression in variable for iterable if condition}
 new_set = {expression for variable if iterable and condition}
 new_set = {expression for variable in iterable while condition}
3. What does the 'if' statement do in set comprehension?
 It filters the elements based on a condition
 It defines the value of each element in the new set
 It defines the variable that takes each value in the iterable
object
 It iterates over the iterable object

4. Which of the following is an example of set comprehension that


filters elements in a list?
 {x for x in numbers if x % 2 == 0}
 {x**2 for x in numbers}
 {word for word in words if any(letter in vowels for letter in
word)}
 All of the above

5. What is the best practice to follow when using set comprehension


in Python?
 Keep it simple, use meaningful variable names, and use curly
braces to increase readability
 Use complex expressions, use short and obscure variable
names, and use parentheses to enclose the set comprehension
 Nest multiple for loops, use the same variable names for
different purposes, and use square brackets to enclose the set
comprehension
 None of the above
Dictionary
A Python dictionary is a collection of key:value pairs.

You can think about them as words and their meaning in an


ordinary dictionary.

Values are said to be mapped to keys.

Dictionary is a built-in Python Data Structure that is mutable.

Mutable means that the object can be modified after it is created. In


the case of dictionaries, you can add, remove, or modify key-value
pairs after the dictionary is created.

However, it is not indexed by a sequence of numbers but indexed


based on keys and can be understood as associative arrays.

In Python, the Dictionary represents the implementation of a


hash-table.

Hash Table:

 A hash table is a data structure that allows for fast retrieval of


values based on keys.

 To locate a value associated with a particular key, the hash


table uses the hash code of the key to find the corresponding
storage location.
What are Keys?

Keys are immutable (which cannot be changed) data types that can
be either strings or numbers.

Keys are unique within a Dictionary and cannot be duplicated


inside a Dictionary.

If it is used more than once, subsequent entries will overwrite the


previous value.

Note: A Dictionary is represented by a pair of curly braces {} in


which enclosed are the key: value pairs separated by a comma.
In Dictionary, keys are hashable.

It means, when you try to access a value associated with a key in a


dictionary, Python computes the hash code of the key and uses it to
quickly locate the corresponding value in the hash table.

The hashing is used to maintain the integrity of the hash table and
also ensure the uniqueness of the hash code.

This ensures that different keys don't accidentally map to the


same location in the hash table, a situation known as a collision.

The hash() function:

It gives the hash value of the key passed to the has function. The
resulting hash value is used as an index (hash code) in a hash table.

These values are then used to lookup for a value associated with its
unique key.

Properties:

 Objects hashed using hash() are irreversible, leading to loss of


information.
 hash() returns hashed value only for immutable objects, hence
can be used as an indicator to check for mutable/immutable
objects.

Example 1:
# initializing objects
int_val = 4
str_val = 'pps'
flt_val = 24.56

# Printing the hash values.


# Notice Integer value doesn't change
# You'll have answer later in article.

print("The integer hash value is : " + str(hash(int_val)))


print("The string hash value is : " + str(hash(str_val)))
print("The float hash value is : " + str(hash(flt_val)))

Output:
The integer hash value is : 4
The string hash value is : -5570917502994512005
The float hash value is : 1291272085159665688
Example 2:

# initializing objects
# tuple is immutable
tuple_val = (1, 2, 3, 4, 5)

# list is mutable
list_val = [1, 2, 3, 4, 5]
# Printing the hash values.
# Notice exception when trying to convert mutable object

print("The tuple hash value is: " + str(hash(tuple_val)))


print("The list hash value is: " + str(hash(list_val)))

Output:

The tuple hash value is: 8315274433719620810

TypeError: unhashable type: 'list'

Creating a Dictionary

We have two main methods to define a dictionary: with curly


braces {} or using the dict() method.

dict1 = {} # Curly braces method

dict2 = dict() # Dict method

# Are the above dictionaries equivalent?


print(type(dict1))
print(type(dict2))
print(dict1 == dict2)
Output: True
We can see that both dictionaries have the same data type and are
equivalent.
Dictionary with key and value
dictionary[key] = value
Example 1:
dict1[key1] = value1
print(dict1[key1]) # Access key1
Output: value1

Example 2:
dict1 = { "key1": "value1"}
print(dict1[key1]) # Access key1
Output: value1

Example 3: Another method is using dict(), in which we supply


keys and values as a keyword argument list or as a list of tuples.
dict1 = dict(key1="value1", key2="value2")
print(dict1) # Access dictionary
Output: {'key1': 'value1', 'key2': 'value2'}

Example 4: List of tuples


dict1 = dict([("key1", "value1"), ("key2", "value2")])
print(dict1) # Access dictionary
Output: {'key1': 'value1', 'key2': 'value2'}
In Python dictionaries, keys should be hashable objects (even if
it's not technically correct, we can also say that the objects should be
immutable).
Thus, mutable data types like lists, aren't allowed.
# Hashing various data types
print(hash(1)) # Integer
print(hash(1.2)) # Float
print(hash("pps")) # String
print(hash((1, 2))) # Tuple
print(hash([1, 2, 3]))

Integers, floats, strings, and tuples are hashable data types (and
they are also immutable) while lists are an unhashable data type
(and they are mutable).
Python uses hash values to quickly access a dictionary's values.

Examples of creating dictionary


Example 1:
pop = [30.55, 2.77, 39.21]
countries = ["afghanistan", "albania", "algeria"]
word_pop = {"afghanistan":30.55, "albania":2.77, "algeria":39.21}
print (word_pop["afghanistan"])
Output: 30.55
Example 2:
# Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']
# From string in countries and capitals, create dictionary europe
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin',
'norway':'oslo'}
print(europe)
Output:
{'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo'}
Example 3: Dictionary keys should be unique
# Dictionary with duplicate keys
duplicated_keys = {"key1": "value1", "key1": "value2", "key1":
"value3"}
# Access key1
print(duplicated_keys["key1"])
Output:
value3
Python Dictionary Methods
1. clear()
The clear() method removes all items from the
dictionary.
# dictionary
numbers = {1: "one", 2: "two"}
# removes all the items from the dictionary
numbers.clear()
print(numbers)
Output: {}
2. get()
In Python, the get() method is a pre-built
dictionary function that enables you to obtain the
value linked to a particular key in a dictionary.
It is a secure method to access dictionary values
without causing a KeyError if the key isn’t present.
dict1 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(dict1.get('Name'))
print(dict1.get('Gender'))
3. items ()
Example 1:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
Output:
dict_items([('brand', 'Ford'), ('model', 'Mustang'),
('year', 1964)])
Example 2:
When an item in the dictionary changes value, the
view object also gets updated:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
car["year"] = 2018
print(x)
Output: dict_items([('brand', 'Ford'), ('model',
'Mustang'), ('year', 2018)])
4. copy()
The copy() method returns a copy of the dictionary.
This method returns a shallow copy of the
dictionary.
It doesn't modify the original dictionary.
Example 1:
original_marks = {'Maths':88, 'Physics':89}
copied_marks = original_marks.copy()
print('Original Marks:', original_marks)
print('Copied Marks:', copied_marks)
Output:
Original Marks: {'Maths':88, 'Physics':89}
Copied Marks: {'Maths':88, 'Physics':89}
Example 2:
original = {1:'one', 2:'two'}
new = original.copy()
print('Orignal: ', original)
print('New: ', new)
Output:
Orignal: {1: 'one', 2: 'two'}
New: {1: 'one', 2: 'two'}
Dictionary copy() Method Vs = Operator
When the copy() method is used, a new dictionary
is created which is filled with a copy of the
references from the original dictionary.
When the = operator is used, a new reference to
the original dictionary is created.
Example 3:
original = {1:'one', 2:'two'}
new = original
# removing all elements from the list
new.clear()
print('new: ', new)
print('original: ', original)
Output:
new: {}
original: {}
5. keys()
The keys() method returns a view object. The view
object contains the keys of the dictionary, as a list.
The view object will reflect any changes done to the
dictionary.
Example 1:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x)
Output: dict_keys(['brand', 'model', 'year'])
Example 2:
When an item is added in the dictionary, the view
object also gets updated:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
car["color"] = "white"
print(x)
Output:
dict_keys(['brand', 'model', 'year', 'color'])
6. pop()
The pop() method removes the specified item from
the dictionary.
The pop() method removes and returns an element
from a dictionary having the given key.
dictionary.pop(keyname, defaultvalue)
keyname: Required. The keyname of the item you
want to remove.
defaultvalue: Optional. A value to return if the
specified key does not exist.
Return value from pop()
The pop() method returns:
If key is found - removed/popped element from
the dictionary
If key is not found - value specified as the second
argument (default)
If key is not found and default argument is not
specified - KeyError exception is raised
Example 1: With key and without default value
marks = { 'Physics': 88, 'Chemistry': 87, 'Math': 82 }
element = marks.pop('Chemistry')
print('Popped Marks:', element)
Output: Popped Marks: 87
Example 2: Without key and with default value
marks = { 'Physics': 88, 'Chemistry': 87, 'Math': 82 }
element = marks.pop('Hindi', 'Subject not found')
print('Popped Marks:', element)
Output: Popped Marks: Subject not found
Example 3: Without key and default value
marks = { 'Physics': 88, 'Chemistry': 87, 'Math': 82 }
element = marks.pop('Hindi')
print('Popped Marks:', element)
Output: KeyError: 'Hindi'
7. popitem()
The popitem() doesn't take any parameters. It
removes the last item from the dictionary:
The popitem() method removes and returns the
(key, value) pair from the dictionary in the Last In,
First Out (LIFO) order.
Returns the latest inserted element (key,value)
pair from the dictionary.
Example 1:
person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}
# ('salary', 3500.0) is inserted at the last, so it is
removed.
result = person.popitem()
print('Return Value = ', result)
print('person = ', person)
Output:
Return Value = ('salary', 3500.0)
person = {'name': 'Phill', 'age': 22}
# inserting a new element pair
person['profession'] = 'Plumber'
# now ('profession', 'Plumber') is the latest element
result = person.popitem()
print('Return Value = ', result)
print('Person = ', person)
Output:
Return Value = ('profession', 'Plumber')
Person = {'name': 'Phill', 'age': 22}
8. setdefault()
Returns the value of the specified key. If the key
does not exist: insert the key, with the specified
value.
Syntax: dict.setdefault(key, default_value)
setdefault() takes a maximum of two parameters:
key - the key to be searched in the dictionary.
default_value (optional) - key with a value
default_value is inserted to the dictionary if the key
is not in the dictionary.
If not provided, the default_value will be None.
Returns:
 Value of the key if it is in the dictionary.
 None if key is not in the dictionary and
default_value is not specified.
 default_value if key is not in the dictionary and
default_value is specified.
Example 1: setdefault(), when key is in the
dictionary.
person = {'name': 'Rohan', 'age': 21}
age = person.setdefault('age')
print('person = ', person)
print('Age = ', age)
Output:
person = {'name': 'Rohan', 'age': 21}
Age = 21
Example 2: setdefault(), when key is not in the
dictionary.
person = {'name': 'Rohan'}
# key is not in the dictionary
salary = person.setdefault('salary')
print('person = ', person)
print('salary = ', salary)
Output:
person = {'name': 'Rohan', 'salary': None}
salary = None
# key is not in the dictionary
# default_value is provided
age = person.setdefault('age', 21)
print('person = ',person)
print('age = ',age)
Output:
person = {'name': 'Rohan', 'age': 21, 'salary': None}
age = 21

9. update()
The update() method is useful whenever we want
to merge dictionaries or add new key:value pairs
using an iterable (iterables are, for instance, lists or
tuples).

The update() method updates the dictionary with


the elements from another dictionary object or from
an iterable of key/value pairs.
Example 1:
marks = {'Physics':67, 'Maths':87}
internal_marks = {'Practical':48}
marks.update(internal_marks)
print(marks)
# Output: {'Physics': 67, 'Maths': 87, 'Practical': 48}
update() Parameters
The update() method takes either a dictionary or
an iterable object of key/value pairs (generally
tuples).
If update() is called without passing parameters, the
dictionary remains unchanged.

Return Value from update()


update() method updates the dictionary with
elements from a dictionary object or an iterable
object of key/value pairs.
It doesn't return any value (returns None).
Example 2:
d = {1: "one", 2: "three"}
d1 = {2: "two"}
# updates the value of key 2
d.update(d1)
print(d)
d1 = {3: "three"}
# adds element with key 3
d.update(d1)
print(d)
Output
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 3: 'three'}

Example 3: update() When Tuple is Passed


dictionary = {'x': 2}
dictionary.update([('y', 3), ('z', 0)])
print(dictionary)
Output
{'x': 2, 'y': 3, 'z': 0}

10. len()
Print the number of items in the dictionary:
d = {1: "one", 2: "three"}
print(len(d))
Output
2
11. Values ()
The values() method returns a view object that
displays a list of all the values in the dictionary.

Example 1:
marks = {'Physics':67, 'Maths':87}
print(marks.values())
Output
dict_values([67, 87])

Return value from values()


values() method returns a view object that displays a
list of all values in a given dictionary.

Example 2: Get all values from the dictionary


# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.values())
Output
dict_values([2, 4, 3])

Example 3: How values() works when a dictionary


is modified?

# random sales dictionary

sales = {'apple': 2, 'orange': 3, 'grapes': 4 }

values = sales.values()

print('Original items:', values)


Output
Original items: dict_values([2, 4, 3])

# delete an item from dictionary

del[sales['apple']]

print('Updated items:', values)


Output
Updated items: dict_values([4, 3])
Nested Dictionary in Python
In Python, a nested dictionary is a dictionary inside a
dictionary. It's a collection of dictionaries into one
single dictionary.
Syntax:
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}

Here, the nested_dict is a nested dictionary with the


dictionary dictA and dictB. They are two dictionary
each having own key and value.
Create a Nested Dictionary
Example 1:
people = {1: {'name': 'John', 'age': '27', ' gender ':
'Male'},
2: {'name': 'Marie', 'age': '22', ' gender ':
'Female'}}
print(people)
Output:
{1: {'name': 'John', 'age': '27', 'gender': 'Male'}, 2:
{'name': 'Marie', 'age': '22', 'gender': 'Female'}}
Access elements of a Nested Dictionary
To access element of a nested dictionary, we use
indexing [] syntax in Python.

Example 2: Access the elements using the [] syntax


people = {1: {'name': 'xyz', 'age': '27', 'gender': 'Male'},
2: {'name': 'yzx', 'age': '22', 'gender': 'Female'}}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['gender'])
Output:
xyz
27
Male

Add element to a Nested Dictionary


Example 3:
people = {1: {'name': 'John', 'age': '27', 'gender': 'Male'},
2: {'name': 'Marie', 'age': '22', 'gender': 'Female'}}

people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['gender'] = 'Female'
people[3]['married'] = 'No'
print(people[3])
Output:
{'name': 'Luna', 'age': '24', 'gender': 'Female', 'married':
'No'}
Explanation: In the above program, we create an
empty dictionary 3 inside the dictionary people.
Then, we add the key:value pair i.e people[3]['Name']
= 'Luna' inside the dictionary 3. Similarly, we do this
for key age, gender and married one by one.

Example 4: Add another dictionary to the nested


dictionary
people = {1: {'name': 'John', 'age': '27', 'gender': 'Male'},
2: {'name': 'Marie', 'age': '22', 'gender': 'Female'},
3: {'name': 'Luna', 'age': '24', 'gender': 'Female',
'married': 'No'}}
people[4] = {'name': 'Peter', 'age': '29', 'gender': 'Male',
'married': 'Yes'}
print(people[4])
Output
{'name': 'Peter', 'age': '29', 'gender': 'Male', 'married':
'Yes'}

Delete elements from a Nested Dictionary


In Python, we use del statement to delete elements
from nested dictionary.
Example 1:
people = {1: {'name': 'John', 'age': '27', 'gender': 'Male'},
2: {'name': 'Marie', 'age': '22', 'gender': 'Female'},
3: {'name': 'Luna', 'age': '24', 'gender': 'Female',
'married': 'No'},
4: {'name': 'Peter', 'age': '29', 'gender': 'Male',
'married': 'Yes'}}
del people[3]['married']
del people[4]['married']
Output:
{'name': 'Luna', 'age': '24', 'gender': 'Female'}
{'name': 'Peter', 'age': '29', 'gender': 'Male'}

Example 2: Delete dictionary from a nested


dictionary
people = {1: {'name': 'John', 'age': '27', 'gender': 'Male'},
2: {'name': 'Marie', 'age': '22', 'gender': 'Female'},
3: {'name': 'Luna', 'age': '24', 'gender': 'Female'},
4: {'name': 'Peter', 'age': '29', 'gender': 'Male'}}
del people[3], people[4]
print(people)
Output
{1: {'name': 'John', 'age': '27', 'gender': 'Male'}, 2:
{'name': 'Marie', 'age': '22', 'gender': 'Female'}}
Loop (iteration) Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value
are the keys of the dictionary, but there are methods
to return the values as well.
Example 1:
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Print all key names in the dictionary, one by one:
for x in dict1:
print(x)

Output:
brand
model
year
Example 2
Print all values in the dictionary, one by one:
for x in dict1:
print(dict1[x])
Output:
Ford
Mustang
1964
Example 3
You can also use the values() function to return values
of a dictionary:
for x in dict1.values():
print(x)

Output:
Ford
Mustang
1964
Iterating Through a Nested Dictionary
Example 1: How to iterate through a Nested
dictionary?
people = {1: {'Name': 'John', 'Age': '27', 'Gender':
'Male'},
2: {'Name': 'Marie', 'Age': '22', 'Gender':
'Female'}}
for p_id, p_info in people.items():
print("\nPerson ID:", p_id)
for key in p_info:
print(key + ':', p_info[key])
Output
Person ID: 1
Name: John
Age: 27
Gender: Male
Person ID: 2
Name: Marie
Age: 22
Gender: Female
Python Check if Key Exists in Dictionary
To determine if a specified key is present in a
dictionary use the in keyword:
Example 1:
Check if "model" is present in the dictionary:
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in dict1:
print("Yes, 'model' is one of the keys in the thisdict
dictionary")
Output
Yes, 'model' is one of the keys in the dict1 dictionary
Dictionary Comprehension
Dictionaries are data types in Python which allows us
to store data in key/value pair.
Dictionary Comprehension can be helpful in creating
new dictionaries from existing dictionaries and
iterables.
Syntax for dictionary comprehension:
{key: value for (key, value) in iterable}

Example 1: Create a dictionary, containing the ages of


some people.
d = {'x': 29, 'y': 24, 'z': 22}
print(d)
Output
{'x': 29, 'y': 24, 'z': 22}
What if we want to add one year to each age and save
the result in a new dictionary? We can do it with a for
loop.
# Dictionary to store new ages
new_d = {}
# Add one year to each age in the dictionary
# items() method displays dictionary keys and values
as a list of tuple pairs (name and age in this case)

for name, age in d.items():


new_d[name] = age + 1
print(new_d)
Output
{'x': 30, 'y': 25, 'z': 23}

However, the for loop can be rewritten in just one line


using dictionary comprehension.

# Add one year to each age in the dictionary using


comprehension
new_d = {name: age + 1 for name, age in d.items()}
print(new_d)
Output:
{'x': 30, 'y': 25, 'z': 23}
Example 2: Let's say we have a list of customers who
visit our store, and we'd like to offer a random
discount to each customer.
We'd like the discount value to be anywhere between
$1 and $100.
Solution:
In Python, random.randint(i,j) returns a random
integer between i and j, where both the end points are
inclusive.
We use this function to generate a discount between
$1 and $100 for every customer in our list.

import random
customers=
["Alex","Bob","Carol","Dave","Flow","Katie","Nate"]
discount_dict = {customer:random.randint(1,100) for
customer in customers}
print(discount_dict)
Output:
{'Alex': 12, 'Bob': 83, 'Carol': 15, 'Dave': 70, 'Flow': 70,
'Katie': 51, 'Nate': 96}
Create a Python Dictionary from Two Iterables
What if we already have pre-defined iterables that
contain the keys and values? Say, we have two lists,
list_1 and list_2 – with list_1 containing the keys and
list_2 containing the corresponding values.
Note 1: We can now use Python's zip() function to zip
these two lists to generate the key-value pairs.
Note 2: The zip function takes in a sequence of
iterables as the argument, and returns an iterator of
tuples, as shown in the image below.

So, the first tuple is the first key-value pair, the


second tuple is the second key-value pair, and in
general, the i-th tuple is the i-th key-value pair.
Syntax: <dict_name> = {<new_key>:<new_value> for
(key,value) in zip(list1,list2)}
 The keys and values are available as tuples, as
we've zipped them together using
the zip() function.
 Now, we loop through this iterator of tuples to get
the key-value pairs for our dictionary.

Example 3: Creating a dictionary of weekly


tempertaures from the list of temperatures and days
days = ["Sunday",
"Monday","Tuesday","Wednesday","Thursday","Friday
","Saturday"]
temp_C = [30.5,32.6,31.8,33.4,29.8,30.2,29.9]
weekly_temp = {day:temp for (day,temp) in
zip(days,temp_C)}
print(weekly_temp)
Output
{'Sunday': 30.5, 'Monday': 32.6, 'Tuesday': 31.8,
'Wednesday': 33.4, 'Thursday': 29.8, 'Friday': 30.2,
'Saturday': 29.9}

Example 4: We have two lists named keys and value


and we are iterating over them with the help of zip()
function.
The zip() function that allows iterating over several
iterables at the same time.

# Lists to represent keys and values


keys = ['a','b','c','d','e']
values = [1,2,3,4,5]
# dict comprehension
myDict = {k:v for (k,v) in zip(keys, values)}
# We can use below too
# myDict = dict(zip(keys, values))
print (myDict)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Example 5: Print the square of the number using list


Sol 1:
square_Dict = {x: x**2 for x in [1,2,3,4,5]}
print(square_Dict)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Sol 2:
square_dict = {num: num*num for num in [1,2,3,4,5]}
print(square_dict)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Example 6: Convert the item price given in dollar to


pound.
#item price in dollars
old_price = {'milk': 1.02, 'coffee': 2.5, 'bread': 2.5}
dollar_to_pound = 0.76
new_price = {item: value*dollar_to_pound for (item,
value) in old_price.items()}
print(new_price)
Output
{'milk': 0.7752, 'coffee': 1.9, 'bread': 1.9}
Dictionary comprehension with conditional
statement
Example 1: Mapping the numbers to their cubes that
are divisible by 4.
newdict = {x: x**3 for x in range(1, 10) if x**3 % 4 ==
0}
print(newdict)
Output
{2: 8, 4: 64, 6: 216, 8: 512}

Example 2: Print the name and age of the person


whose age is even no.
original_dict = {'jack': 38, 'michael': 48, 'guido': 57,
'john': 33}
even_dict = {k: v for (k, v) in original_dict.items() if v %
2 == 0}
print(even_dict)
Output
{'jack': 38, 'michael': 48}
Multiple if Conditional Dictionary Comprehension
Example 1:
original_dict = {'jack': 38, 'michael': 48, 'guido': 57,
'john': 33}
new_dict = {k: v for (k, v) in original_dict.items() if v %
2 != 0 if v < 40}
print(new_dict)
Output
{'john': 33}

if-else Conditional Dictionary Comprehension


Creating a dictionary from an existing dictionary
Syntax: <dict_name> = {<new_key>:<new_value> for
(key,value) in <dict>.items() if <condition>}
Example 1: WRT a program to list out the old and
young person.
original_dict = {'jack': 38, 'michael': 48, 'guido': 57,
'john': 33}

new_dict_1 = {k: ('old' if v > 40 else 'young')


for (k, v) in original_dict.items()}
print(new_dict_1)
Output
{'jack': 'young', 'michael': 'old', 'guido': 'old', 'john':
'young'}

Using nested dictionary comprehension


Example 2
# given string
d="DLD"
# using dictionary comprehension
dic = {
x: {y: x + y for y in d} for x in d
}
print(dic)
Output
{'D': {'D': 'DD', 'L': 'DL'}, 'L': {'D': 'LD', 'L': 'LL'}}
String
A string is an object that contains a sequence of characters.

A character is a string of length one.

A single character is also a string in Python.

Ironically, the character data type is absent in the Python


programming language.

However, we find the character data type in other programming


languages like C, and Java.

We can declare a Python string using a single quote, a double quote,


a triple quote, or the str() function.

Example

# A single quote string

single_quote = 'a' # This is an example of a character in other


programming languages. But, it is a string in Python.

# Another single quote string

another_single_quote = 'Welcome to PPS.'

# A double quote string

double_quote = "aa"
# Another double-quote string

another_double_quote = "Complete the assignment within time


otherwise ready for the penalty"

# A triple quote string

triple_quote = '''aaa'''

# Also a triple quote string

another_triple_quote = """Welcome to the Python programming


language. Ready, 1, 2, 3, Go!"""

# Using the str() function

string_function = str(123.45) # str() converts float data type to string


data type

# Another str() function

another_string_function = str(True) # str() converts a boolean data


type to string data type

# Multiline String

message = """
Welcome to Galgotias University
Welcome to MCA Course
"""
# An empty string with single quote

empty_string = ' '


# An empty string with double quote

second_empty_string = ""

# An empty with triple double quote and triple single cloging


quote

third_empty_string = """""" # This is also an empty string: ''''''

Another way of getting strings in Python is using the input() function.

The input() function allows us to insert values into a program with


the keyboard.

The inserted values are read as a string, but we can convert them into
other data types.

# Inputs into a Python program

input_float = input() # Type in: 3.142

input_boolean = input() # Type in: True

# Convert inputs into other data types

convert_float = float(input_float) # converts the string data type to a


float

convert_boolean = bool(input_boolean) # converts the string data


type to a bool
Note:

We use the type() function to determine the data type of an object in


Python. It returns the class of the object.

When the object is a string, it returns the str class.

Similarly, it returns dict, int, float, tuple, bool class when the object
is a dictionary, integer, float, tuple, or Boolean, respectively.

The ASCII Table vs. Python String Character


The American Standard Code for Information Interchange (ASCII)
was developed to help us map characters or texts to numbers
because sets of numbers are easier to store in the computer
memory than texts.

ASCII encodes 128 characters mainly in the English language that are
used in processing information in computers and programming.

The English characters encoded by ASCII include lowercase letters (a-


z), uppercase letters (A-Z), digits (0-9), and symbols such as
punctuation marks.

The ord() function converts a Python string of length one (a


character) to its decimal representation on the ASCII table, while the
chr() function converts the decimal representation back to a string.
Example: # Convert uppercase characters to their ASCII decimal
numbers

import string

ascii_upper_case = string.ascii_uppercase

# Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ

for one_letter in ascii_upper_case[:5]: # Loop through ABCDE

print(ord(one_letter))

Output:

65
66
67
68
69

Example: Convert digit characters to their ASCII decimal numbers

ascii_digits = string.digits # Output: 0123456789

for one_digit in ascii_digits[:5]: # Loop through 01234


print(ord(one_digit))
Output: decimal representation of 01234
48
49
50
51
52
We can also carry out the reverse operation with the chr() function,
whereby we convert decimal numbers on the ASCII table to their
Python string characters.

decimal_rep_ascii = [37, 44, 63, 82, 100]

for one_decimal in decimal_rep_ascii:


print(chr(one_decimal))

Output:
%
,
?
R
d
>
String Properties
1. Zero Index: The first element in a string has an index of zero, while
the last element has an index of len(string) - 1.
Example:
immutable_string = "Accountability"

print(len(immutable_string))
print(immutable_string.index('A'))
print(immutable_string.index('y'))

Output:
14
0
13
2. Immutability: This means that we cannot update the characters in
a string.

For example, we cannot delete an element from a string or try to


assign a new element at any of its index positions. If we try to
update the string, it throws a TypeError.

Example:

immutable_string = "Accountability"

# Assign a new element at index 0


immutable_string[0] = 'B'

TypeError: 'str' object does not support item assignment

We can, however, reassign a string to the immutable_string


variable, but we should note that they aren't the same string
because they don't point to the same object in memory. Python
doesn't update the old string object; it creates a new one, as we can
see by the ids:

Example:

immutable_string = "Accountability"
print(id(immutable_string))

immutable_string = "Bccountability"
print(id(immutable_string)

test_immutable = immutable_string
print(id(test_immutable))
Output:
2815347848432
2815347848496
2815347848496

Conclusion:

Both immutable_string variables point to different addresses in


memory.

We assigned the last immutable_string variable to test_immutable


variable. You can see that test_immutable variable and the last
immutable_string variable point to the same address.

3. Concatenation

joining two or more strings together to get a new string with the +
symbol.

Example:

first_string = "PPS"
second_string = " Subject"
third_string = "Python programming path"

fourth_string = first_string + second_string


print(fourth_string)

fifth_string = fourth_string + " " + third_string


print(fifth_string)

Output
PPS Subject
PPS Subject Python programming path

4. Repetition

A string can be repeated with the * symbol.

print("PPS" * 3)

Output

PPSPPSPPS

5. Indexing and Slicing

We can access any element in a string with its index value. We can
also take subsets of a string by slicing between two index values.

main_string = "I will learn Python and C in PPS Subject.

# Index 0
print(main_string[0]) # OUTPUT: I

# Index 1
print(main_string[1]) # OUTPUT: White Space

# Check if Index 1 is whitespace


print(main_string[1].isspace()) # OUTPUT: True

# Slicing 1
print(main_string[0:11]) # OUTPUT: I will lear

# Slicing 2:
print(main_string[-18:]) # OUTPUT: C in PPS Subject.
# Slicing and concatenation
print(main_string[0:11] + ". " + main_string[-18:])

# OUTPUT: I will lear. C in PPS Subject.

6. Compare Two Strings

We use the == operator to compare two strings. If two strings are


equal, the operator returns True. Otherwise, it returns False.

Example

str1 = "Hello, world!"


str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2) #OUTPUT: False

# compare str1 and str3


print(str1 == str3) #OUTPUT: True

Iterate Through a Python String

We can iterate through a string using a for loop.

greet = 'Hello'

# iterating through greet string


for letter in greet:
print(letter)
Output
H
e
l
l
o

Looping operation with for loop and enumerate

for idx, value in enumerate(greet):


print(idx, value)

Output
0H
1e
2l
3l
4o

String Membership Test

We can test if a substring exists within a string or not, using the


keyword in.

print('P' in 'PPS') # OUTPUT: True


print('P' not in 'PPS') # OUTPUT: False
Deleting/Updating from a String

 In Python, the Updation or deletion of characters from a String


is not allowed.

 Although deletion of the entire String is possible with the use


of a built-in del keyword.

 This is because Strings are immutable, hence elements of a


String cannot be changed once assigned.

 Only new strings can be reassigned to the same name.

Updating a character

A character of a string can be updated in Python by first converting


the string into a Python List and then updating the element in the list.

As lists are mutable in nature, we can update the character and


then convert the list back into the String.

Another method is using the string slicing method. Slice the string
before the character you want to update, then add the new character
and finally add the other part of the string again by string slicing.

Example:

# Python Program to Update


# character of a String

String1 = "Hello, I'm a boy"


print("Initial String: ")
print(String1)
Output

Initial String:
Hello, I'm a boy

# Updating a character of the String


## As python strings are immutable, they don't support item
updation directly
### there are following two ways

# Rule 1
list1 = list(String1)
list1[2] = 'p'
String2 = ' '.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)

Output

Updating character at 2nd Index:


Heplo, I'm a boy

# Rule 2
String3 = String1[0:2] + 'p' + String1[3:]

print (String1[0:2])

print (String1[3:])

print(String3)
Output
He
lo, I'm a boy
Heplo, I'm a boy

Updating Entire String

As Python strings are immutable in nature, we cannot update the


existing string.

We can only assign a completely new value to the variable with the
same name.

Example

# Python Program to Update


# entire String

String1 = "Hello, I'm a boy"


print("Initial String: ")
print(String1)

Output

Initial String:
Hello, I'm a boy

# Updating a String
String1 = "Welcome to PPS Class"
print("\nUpdated String: ")
print(String1)
Output

Updated String:
Welcome to PPS Class

Deleting a character

Python strings are immutable, that means we cannot delete a


character from it.

When we try to delete the character using the del keyword, it will
generate an error.

Example

# Python Program to delete


# character of a String

String1 = "Hello, I'm a boy"


print("Initial String: ")
print(String1)

Output

Initial String:
Hello, I'm a Geek

print("Deleting character at 2nd Index: ")


del String1[2]
print(String1)
Output

Deleting character at 2nd Index:


TypeError: 'str' object doesn't support item deletion

Slicing

But using slicing we can remove the character from the original
string and store the result in a new string.

Example

# Python Program to Delete


# characters from a String

String1 = "Hello, I'm a boy"


print("Initial String: ")
print(String1)

Output

Initial String:
Hello, I'm a boy

# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]

print (String1[0:2])
print (String1[3:])

print("\nDeleting character at 2nd Index: ")


print(String2)
Output

He
lo, I'm a boy

Deleting character at 2nd Index:


Helo, I'm a boy

Deleting Entire String

Deletion of the entire string is possible with the use of del


keyword. Further, if we try to print the string, this will produce an
error because the String is deleted and is unavailable to be printed.

Example

# deleting the entire string

String1 = "Hello, I'm a boy"


print("Initial String: ")
print(String1)

Output

Initial String:
Hello, I'm a boy

# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
Output

Deleting entire String:


NameError: name 'String1' is not defined

String and relational operators

When two strings are compared using relational operators (>, <, ==,
etc.), the elements of the two strings are compared by their ASCII
decimal numbers index by index.

print('a' > 'b')


print('abc' > 'b')

Output
False
False

In both cases, the output is False. The relational operator first


compared the ASCII decimal numbers of the elements on index 0 for
both strings. Since b is greater than a, it returns False; the ASCII
decimal numbers of the other elements, and the length of the strings
do not matter in this case.

Note: When the strings are of the same length, it compares the ASCII
decimal numbers of each element from index 0 until it finds
elements with different ASCII decimal numbers. For example:

print('abd' > 'abc')

Output: True
In the above code snippet, the first two elements have the same
ASCII decimal numbers; however, there is a mismatch in the third
element, and since d is greater than c, it returns True.

In a situation where all the ASCII numbers for the elements match,
the longer string is greater than the shorter one. For example:

print('abcd' > 'abc')


True

String Methods

1. str.split(sep=None, maxsplit=-1):

The string split method contains two attributes: sep and maxsplit.
When this method is called with its default values, it splits the string
anywhere there is a whitespace. This method returns a list of
strings:

string = "Apple, Banana, Orange, Blueberry"


print(string.split())

Output

['Apple,', 'Banana,', 'Orange,', 'Blueberry']

We can see that the string isn't split nicely because the split string
contains ,. We can use sep=','to split wherever there is a ,:

print(string.split(sep=','))
Output

['Apple', ' Banana', ' Orange', ' Blueberry']


This is better than the previous split. However, we can see whitespace
before some of the split strings. We can remove this with (sep=', '):

print(string.split(sep=', '))

Output

['Apple', 'Banana', 'Orange', 'Blueberry']

Sometimes, we don't want to split the maximum number of times. We


can use the maxsplit attribute to specify the number of times we
intend to split:

print(string.split(sep=', ', maxsplit=1))

Output: ['Apple', 'Banana, Orange, Blueberry']

print(string.split(sep=', ', maxsplit=2))

Output: ['Apple', 'Banana', 'Orange, Blueberry']

2. str.strip([chars])

We remove trailing whitespaces or characters from both sides of


the string with the strip method.

string = " Apple Apple Apple no apple in the box apple apple "

stripped_string = string.strip()
print(stripped_string)
Output: Apple Apple Apple no apple in the box apple apple

Remove the trailing whitespaces or characters from the left


left_stripped_string = (
stripped_string
.lstrip('Apple')
.lstrip()
.lstrip('Apple')
.lstrip()
.lstrip('Apple')
.lstrip()
)
print(left_stripped_string)

Output: no apple in the box apple apple

Capitalize the string

capitalized_string = left_stripped_string.capitalize()
print(capitalized_string)

Output: No apple in the box apple apple

Remove the trailing whitespaces or characters from the right

right_stripped_string = (
capitalized_string
.rstrip('apple')
.rstrip()
.rstrip('apple')
.rstrip()
)
print(right_stripped_string)
Output: No apple in the box

In the above code snippet, we have used the lstrip and rstrip
methods that remove trailing whitespaces or characters from the
left and right sides of the string respectively. We have also used the
capitalize method, which converts a string to a sentence case.

3. str.zfill(width)

example = "0.8" # len(example) is 3


example_zfill = example.zfill(5) # len(example_zfill) is 5
print(example_zfill)

Output: 000.8

4. str.isalpha()

This method returns True if all the characters in the string are
alphabets; otherwise, it returns False:

# Alphabet string
alphabet_one = "Learning"
print(alphabet_one.isalpha())

# Contains whitspace
alphabet_two = "Learning Python"
print(alphabet_two.isalpha())

# Contains comma symbols


alphabet_three = "Learning,"
print(alphabet_three.isalpha())
Similarly, str.isalnum() returns True if the string characters are
alphanumeric; str.isdecimal() returns True if the string characters
are decimal; str.isdigit() returns True if the string characters are
digits; and str.isnumeric() returns True if the string characters are
numeric.
str.islower() returns True if all the characters in the string are
lowercase. str.isupper() returns True if all the characters in the
string are uppercase, and str.istitle() returns True if the first letter
of every word is capitalized:
# islower()
string_one = "Artificial Neural Network"
print(string_one.islower()) # False

string_two = string_one.lower() # converts string to lowercase


print(string_two.islower()) # True

# isupper()
string_three = string_one.upper() # converts string to uppercase
print(string_three.isupper()) # True

# istitle()
print(string_one.istitle()) # True
String with Suffix and Prefix
sentences = ['Time to master data science', 'I love statistical
computing', 'Eat, sleep, code']
# endswith()
for one_sentence in sentences:
print(one_sentence.endswith(('science', 'computing', 'Code')))
Output
True
True
False

# startswith()
for one_sentence in sentences:
print(one_sentence.startswith(('Time', 'I ', 'Ea')))
Output
True
True
True

str.find(substring)
It returns the lowest index if the substring is present in the string;
otherwise, it returns -1.
str.rfind(substring) returns the highest index.
The str.index(substring) and str.rindex(substring) also return
the lowest and highest index of the substring respectively if found.
If the substring isn't present in the string, they raise ValueError.

string = "programming"
# find() and rfind() examples
print(string.find('m'))
print(string.find('pro'))
print(string.rfind('m'))
print(string.rfind('game'))

Output
6
0
7
-1

# index() and rindex() examples


print(string.index('m'))
print(string.index('pro'))
print(string.rindex('m'))
print(string.rindex('game'))
Output
6
0
7
ValueError: substring not found

You might also like