0% found this document useful (0 votes)
7 views54 pages

UNIT 2 Study Materials & Sample Programs

The document provides an overview of Python dictionaries, lists, strings, and tuples, detailing their characteristics, creation methods, and common operations. It explains how to access, add, update, and remove items in these data structures, along with examples for clarity. Additionally, it highlights the immutability of tuples and the mutable nature of lists and dictionaries.
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)
7 views54 pages

UNIT 2 Study Materials & Sample Programs

The document provides an overview of Python dictionaries, lists, strings, and tuples, detailing their characteristics, creation methods, and common operations. It explains how to access, add, update, and remove items in these data structures, along with examples for clarity. Additionally, it highlights the immutability of tuples and the mutable nature of lists and dictionaries.
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/ 54

Dictionaries in Python

A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary
can be of any data type and can be duplicated, whereas keys can’t be repeated and must be
immutable.

The data is stored in key:value pairs in dictionaries, which makes it easier to find values.

How to Create a Dictionary

In Python, a dictionary can be created by placing a sequence of elements within curly {} braces,
separated by a ‘comma’.

# Example create dictionary using { }

d2 = {1: ‘Chennai', 2: ‘Mumbai', 3: ‘Delhi'}

print(d2)

# Example create dictionary using dict() constructor

d3 = dict(a = “ball", b = “bat", c = “cricket")

print(d3)

 Dictionary keys are case sensitive: the same name but different cases of Key will be treated
distinctly.
 Keys must be immutable: This means keys can be strings, numbers, or tuples but not lists.
 Keys must be unique: Duplicate keys are not allowed and any duplicate key will overwrite
the previous value.
 Dictionary internally uses Hashing. Hence, operations like search, insert, delete can be
performed in Constant Time.

Accessing Dictionary Items


We can access a value from a dictionary by using the key within square brackets or get() method.

# example
d = { "name": "Alice", 1: "Python", (1, 2): [1,2,4] }

# Example Access using key


print(d["name"]) # output – “Alice”

# Example Access using get()


print(d.get("name") # output – “Alice”

Adding and Updating Dictionary Items


We can add new key-value pairs or update existing keys by using assignment.
# Example Adding a new key-value pair
d["age"] = 22
Print (d)

# Example Updating an existing value


d1[5] = “Success"
print(d1)

Removing Dictionary Items


We can remove items from dictionary using the following methods:

 del: Removes an item by key.


 pop(): Removes an item by key and returns its value.
 clear(): Empties the dictionary.
 popitem(): Removes and returns the last key-value pair

#Example- Using del to remove an item

del d2[“2"]

print(d2)

d2[“4"] = Kolkata # I want to add an key:value

print(d2)

# Example Using pop() to remove an item and return the value

val = d1.pop(4)

print(val)

# Example Using popitem to removes and returns the last key-value pair.

key, val = d1.popitem()

print("Key: “, {key}, “Value:”, {val})


Nested Dictionaries

d = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

print(d) # output {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all
types of items (including another list) in a list. A list may contain mixed type of items, this is possible
because a list mainly stores references at contiguous locations and actual items may be stored at
different locations. List can contain duplicate items. List in Python are Mutable. Hence, we can
modify, replace or delete the items. Lists are ordered. It maintains the order of elements based on
how they are added. Accessing items in List can be done directly using their position (index), starting
from 0.

# example

a = [10, 20, 15]

print(a[0]) # access first item

a.append(11) # add item

a.remove(20) # remove item

print(a)

Creating a List

Using Square Brackets


# List of integers

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

# List of strings

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

# Mixed data types

c = [1, 'hello', 3.14, True]

print(a)

print(b)

print(c)

Using list() Constructor

We can also create a list by passing an iterable (like a string, tuple, or another list) to list() function.

# From a tuple
a = list((1, 2, 3, 'apple', 4.5))

print(a)

Creating List with Repeated Elements

We can create a list with repeated elements using the multiplication operator.

# Create a list [2, 2, 2, 2, 2]

a = [2] * 5

# Create a list [0, 0, 0, 0, 0, 0, 0]

b = [0] * 7

print(a)

print(b)

Accessing List Elements

Elements in a list can be accessed using indexing. Python indexes start at 0, so a[0] will access the
first element, while negative indexing allows us to access elements from the end of the list. Like
index -1 represents the last elements of list.

a = [10, 20, 30, 40, 50]

# Access first element

print(a[0]) # ouput is 10

# Access last element

print(a[-1]) # output is 50

Adding Elements into List

We can add elements to a list using the following methods:

 append(): Adds an element at the end of the list.


 extend(): Adds multiple elements to the end of the list.
 insert(): Adds an element at a specific position.

# Initialize an empty list

a = []

# Adding 10 to end of list

a.append(10)

print("After append(10):", a)
# Inserting 5 at index 0

a.insert(0, 5)

print("After insert(0, 5):", a)

# Adding multiple elements [15, 20, 25] at the end

a.extend([15, 20, 25])

print("After extend([15, 20, 25]):", a)

# Output -After append(10): [10]

# Output -After insert(0, 5): [5, 10]

# Output -After extend([15, 20, 25]): [5, 10, 15, 20, 25]

Updating Elements into List

We can change the value of an element by accessing it using its index.

a = [10, 20, 30, 40, 50]

# Change the second element

a[1] = 25

print(a)

# output - [10, 25, 30, 40, 50]

Removing Elements from List

We can remove elements from a list using:

 remove(): Removes the first occurrence of an element.


 pop(): Removes the element at a specific index or the last element if no index is specified.
 del statement: Deletes an element at a specified index.

a = [10, 20, 30, 40, 50]

# Removes the first occurrence of 30

a.remove(30)

print("After remove(30):", a)

# Removes the element at index 1 (20)

popped_val = a.pop(1)

print("Popped element:", popped_val)


print("After pop(1):", a)

# Deletes the first element (10)

del a[0]

print("After del a[0]:", a)

# ouput - After remove(30): [10, 20, 40, 50]

# ouput - Popped element: 20

# ouput - After pop(1): [10, 40, 50]

# ouput - After del a[0]: [40, 50]

Iterating Over Lists

We can iterate the Lists easily by using a for loop or other iteration methods. Iterating over lists is
useful when we want to do some operation on each item or access specific items based on certain
conditions. Let’s take an example to iterate over the list using for loop.

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

# Iterating over the list

for item in a:

print(item)

Output

apple

banana

cherry

Nested Lists in Python

A nested list is a list within another list, which is useful for representing matrices or tables. We can
access nested elements by chaining indexes.

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

# Access element at row 2, column 3


print(matrix[1][2])

Output

6
Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This
includes letters, numbers, and symbols. Python has no character data type so single
character is a string of length 1.

Creating a String-

Strings can be created using either single (‘) or double (“) quotes.

# program to generate a string

s1 = ‘ABC'

s2 = “XYZ"

print(s1)

print(s2)

Multi-line Strings-

If we need a string to span multiple lines then we can use triple quotes (”’ or “””).

# Sample program for multi line string

s = """I am in second year

at Hindustan"""

print(s)

# output

# I am in second

# year at Hindustan

Accessing characters in Python String

Strings in Python are sequences of characters, so we can access individual characters


using indexing. Strings are indexed starting from 0 and 1 from end. This allows us to retrieve
specific characters from the string.

Ex: Accessing characters

s = “LITERATURE"

print(s[0]) #ouput=L
print(s[4]) #output=R

Note: Accessing an index out of range will cause an IndexError. Only integers are allowed as
indices and using a float or other types will result in a TypeError.

Access string with Negative Indexing

Python allows negative address references to access characters from back of the String,

e.g. -1 refers to the last character, -2 refers to the second last character, and so on.

# sample program

s = “LITERATURE"

print(s[-10])

print(s[-5])

String Slicing

Slicing is a way to extract portion of a string by specifying the start and end indexes.

The syntax for slicing is string[start:end], where start starting index and end is stopping
index (excluded).

s = “ALLTHEBEST"

# Retrieves characters from index 1 to 3: ‘LLT'

print(s[1:4])

# Retrieves characters from beginning to index 2: ‘ALL'

print(s[:3])

# Retrieves characters from index 3 to the end: ‘THEBEST'

print(s[3:])

# Reverse a string

print(s[::-1])

#output is ‘TSEBEHTLLA’
String Immutability

Strings in Python are immutable. This means that they cannot be changed after they are
created. If we need to manipulate strings then we can use methods like concatenation,
slicing, or formatting to create new strings based on the original.

# to change the first character in the string

s = “LOVEINDIA"

# s[0] = 'I' # Uncommenting this line will cause a TypeError

# Instead, create a new string

s = “I" + s[0:]

print(s)

#output is ‘ILOVEINDIA’

Deleting a String

In Python, it is not possible to delete individual characters from a string since strings are
immutable. However, we can delete an entire string variable using the del keyword.

# example

s = "GfG"

del s # Deletes entire string

Note: After deleting the string using del and if we try to access s then it will result in
a NameError because the variable no longer exists.

Updating a String

To update a part of a string we need to create a new string since strings are immutable.

# example

s = "hello Alice“

# Update- “h” by “H”

S1 = "H" + s[1:]

print(s1)
# replace “Alice" with “Varun"

S2= s1.replace(“Alice", “Varun")

print(s2)

Common String Methods- Python provides a various built-in methods to manipulate strings.
len(): The len() function returns the total number of characters in a string.

s = “Computer"

print(len(s))

# output: 8

Common String Methods

upper() and lower():

upper() method converts all characters to uppercase.

lower() method converts all characters to lowercase.

s = "Hello World"

print(s.upper()) # output: HELLO WORLD

print(s.lower()) # output: hello world

strip() and replace():

strip() removes leading and trailing whitespace from the string

replace(old, new) replaces all occurrences of a specified substring with another.

# Remove spaces from both ends

s = " ABC "

print(s.strip())

# Replaces 'fun' with 'awesome'

s = "Python is fun"

print(s.replace("fun", "awesome"))

Concatenating and Repeating Strings

We can concatenate strings using + operator and repeat them using * operator.
Strings can be combined by using + operator.

s1 = "Hello"

s2 = "World"

s3 = s1 + " " + s2

print(s3)

# output is ‘Hello World’

We can repeat a string multiple times using * operator.

s = "Hello "

print(s * 3)

# output ‘Hello Hello Hello ‘

Formatting Strings

Python provides several ways to include variables inside strings.

Using f-strings

The simplest and most preferred way to format strings is by using f-strings.

name = "Alice"

age = 22

print(f"Name:”, {name}, “Age: “, {age})

#output is ‘Name: Alice, Age: 22’

Using format()

Another way to format strings is by using format() method.

# example program

s = "My name is {} and I am {} years old.“

s1= s.format("Alice", 22)

print(s1)
Using in for String Membership Testing

The in keyword checks if a particular substring is present in a string.

s = “ANECDOTE"

print(“DOT" in s) #output True

print(“XYZ" in s) #output False


Tuples in Python

Python Tuple is a collection of objects separated by commas. A tuple is similar to a Python list in
terms of indexing, nested objects, and repetition but the main difference between both is Python
tuple is immutable, unlike the Python list which is mutable.

# Note : In case of list, we use square

# brackets []. Here we use round brackets ()

t = (10, 20, 30)

print(t) # (10, 20, 30)

print(type(t)) # <class 'tuple'>

What is Immutable in Tuples?

Unlike Python lists, tuples are immutable. Some Characteristics of Tuples in Python.

Like Lists, tuples are ordered and we can access their elements using their index values

We cannot update items to a tuple once it is created.

Tuples cannot be appended or extended.

We cannot remove items from a tuple once it is created.

t = (1, 2, 3, 4, 5)

# tuples are indexed

print(t[1]) # 2

print(t[4]) # 5

# tuples contain duplicate elements

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

print(t) # (1, 2, 3, 4, 2, 3)

# updating an element

t[1] = 100

print(t) # TypeError: 'tuple' object does not support item assignment

Accessing Values in Python Tuples

Tuples in Python provide two ways by which we can access the elements of a tuple.

Python Access Tuple using a Positive Index


Using square brackets we can get the values from tuples in Python.

t = (10, 5, 20)

print("Value in t[0] = ", t[0])

print("Value in t[1] = ", t[1])

print("Value in t[2] = ", t[2])

Output

Value in t[0] = 10

Value in t[1] = 5

Value in t[2] = 20

Access Tuple using Negative Index

In the above methods, we use the positive index to access the value in Python, and here we will use
the negative index within [].

t = (10, 5, 20)

print("Value in t[-1] = ", t[-1])

print("Value in t[-2] = ", t[-2])

print("Value in t[-3] = ", t[-3])

Output

Value in t[-1] = 20

Value in t[-2] = 5

Value in t[-3] = 10

Different Operations Related to Tuples

Below are the different operations related to tuples in Python:

Traversing Items of Python Tuples

Like List Traversal, we can traverse through a tuple using for loop.

# Define a tuple

t = (1, 2, 3, 4, 5)

# Traverse through each item in the tuple

for x in t:
print(x, end=" ")

Output

12345

Concatenation of Python Tuples

To Concatenation of Python Tuples, we will use plus operators (+).

# Code for concatenating 2 tuples

t1 = (0, 1, 2, 3)

t2 = ('hai', 'welcome')

# Concatenating above two

print(t1 + t2)

Output

(0, 1, 2, 3, 'hai', 'welcome')

Nesting of Python Tuples

A nested tuple in Python means a tuple inside another tuple.

# Code for creating nested tuples

t1 = (0, 1, 2, 3)

t2 = ('hai', 'welcome')

t3 = (t1, t2)

print(t3)

Output

((0, 1, 2, 3), ('hai', 'welcome'))

Repetition Python Tuples

We can create a tuple of multiple same elements from a single element in that tuple.

# Code to create a tuple with repetition

t = ('python',)*3

print(t)

Output
('python', 'python', 'python')

Slicing Tuples in Python

Slicing a Python tuple means dividing a tuple into small tuples using the indexing method. In this
example, we slice the tuple from index 1 to the last element. In the second print statement, we
printed the tuple using reverse indexing. And in the third print statement, we printed the elements
from index 2 to 4.

# code to test slicing

t = (0 ,1, 2, 3)

print(t[1:])

print(t[::-1])

print(t[2:4])

Output

(1, 2, 3)

(3, 2, 1, 0)

(2, 3)

Deleting a Tuple in Python

In this example, we are deleting a tuple using ‘del’ keyword. The output will be in the form of error
because after deleting the tuple, it will give a Name Error.

Note: Remove individual tuple elements are not possible, but we can delete the whole Tuple using
Del keyword.

# Code for deleting a tuple

t = ( 0, 1)

del t

print(t) # NameError: name 't' is not defined

Finding the Length of a Python Tuple

To find the length of a tuple, we can use Python’s len() function and pass the tuple as the parameter.

# Code for printing the length of a tuple

t = ('python', 'geek')

print(len(t)) # 2
Multiple Data Types With Tuple

Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple
datatypes.

# tuple with different datatypes

t = ("immutable", True, 23)

print(t)

Converting a List to a Tuple

We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its
parameters.

# Code for converting a list and a string into a tuple

a = [0, 1, 2]

t = tuple(a)

print(t)

Output: (0, 1, 2)

Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are
taken as elements), and converts them to a tuple

Tuples in a Loop

We can also create a tuple with a single element in it using loops.

# python code for creating tuples in a loop

t = ('gfg',)

# Number of time loop runs

n=5

for i in range(int(n)):

t = (t,)

print(t)

Output

(('gfg',),)

((('gfg',),),)

(((('gfg',),),),)
((((('gfg',),),),),)

(((((('gfg',),),),),),)

Different Ways of Creating a Tuple

Using round brackets

t = ("gfg", "Python")

print(t)

Without Brackets

# Creating a tuple without brackets

t = 4, 5, 6

print(t) # Output: (4, 5, 6)

Tuple Constructor

# Creating a tuple using the tuple() constructor

t = tuple([7, 8, 9])

print(t) # Output: (7, 8, 9)

Empty Tuple

# Creating an empty tuple

t = ()

print(t) # Output: ()

Single Element Tuple

# Creating a single-element tuple

t = (10, ) # Comma is important here

print(t) # Output: (10,)

print(type(t))

# What if we do not use comma

t = (10) # This an integer (not a tuple)

print(t)

print(type(t))
Using Tuple Packing

# Tuple packing

a, b, c = 11, 12, 13

t = (a, b, c)

print(t) # Output: (11, 12, 13)


Python Sets

Python set is an unordered collection of multiple items having different datatypes. In Python, sets
are mutable, unindexed and do not contain duplicates. The order of elements in a set is not
preserved and can change.

Creating a Set in Python

In Python, the most basic and efficient method for creating a set is using curly braces.

set1 = {1, 2, 3, 4}

print(set1) # {1, 2, 3, 4}

Using the set() function

Python Sets can be created by using the built-in set() function with an iterable object or a sequence
by placing the sequence inside curly braces, separated by a ‘comma’.

Note: A Python set cannot have mutable elements like a list or dictionary, as it is immutable.

# Creating a Set

set1 = set()

print(set1)

set1 = set("ALLTHEBEST")

print(set1)

# Creating a Set with the use of a List

set1 = set(["ALL", "THE", "BEST"])

print(set1)

# Creating a Set with the use of a tuple

tup = ("ALL", "THE", "BEST")

print(set(tup))

# Creating a Set with the use of a dictionary

d = {"ALL": 1, "THE": 2, "BEST": 3}


print(set(d))

Unordered, Unindexed and Mutability

In set, the order of elements is not guaranteed to be the same as the order in which they were
added. The output could vary each time we run the program. Also the duplicate items entered are
removed by itself.

Sets do not support indexing. Trying to access an element by index (set[0]) raises a TypeError.

We can add elements to the set using add(). We can remove elements from the set using remove ().
The set changes after these operations, demonstrating its mutability. However, we cannot change its
items directly.

Adding Elements to a Set in Python

We can add items to a set using add() method and update() method.

add() method can be used to add only a single item.

To add multiple items we use update() method.

# Creating a set

set1 = {1, 2, 3}

# Add one item

set1.add(4)

# Add multiple items

set1.update([5, 6])

print(set1)

Output

{1, 2, 3, 4, 5, 6}

Accessing a Set in Python

We can loop through a set to access set items as set is unindexed and do not support accessing
elements by indexing. Also we can use in keyword which is membership operator to check if an item
exists in a set.

set1 = set(["welcome", "to ", "hindustan."])

# Accessing element using For loop

for i in set1:

print(i, end=" ") # welcome to Hindustan.


# Checking the element

# using in keyword

print("to" in set1) # True

Removing Elements from the Set in Python

We can remove an element from a set in Python using several methods: remove(), discard() and
pop(). Each method works slightly differently :

Using remove() Method or discard() Method

Using pop() Method

Using clear() Method

Using remove() Method or discard() Method

remove() method removes a specified element from the set. If the element is not present in the set,
it raises a KeyError. discard() method also removes a specified element from the set. Unlike
remove(), if the element is not found, it does not raise an error.

# Using Remove Method

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

set1.remove(3)

print(set1) # {1, 2, 4, 5}

# Attempting to remove an element that does not exist

try:

set1.remove(10)

except KeyError as e:

print("Error:", e) # Error: 10

# Using discard() Method

set1.discard(4)

print(set1) # {1, 2, 5}

# Attempting to discard an element that does not exist

set1.discard(10) # No error raised

print(set1) # {1, 2, 5}

Using pop() Method


pop() method removes and returns an arbitrary element from the set. This means we don’t know
which element will be removed. If the set is empty, it raises a KeyError.

Note: If the set is unordered then there’s no such way to determine which element is popped by
using the pop() function.

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

val = set1.pop()

print(val) # 1

print(set1) # {2, 3, 4, 5}

Using clear() Method

clear() method removes all elements from the set, leaving it empty.

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

set1.clear()

print(set1) # set()

Frozen Sets in Python

A frozenset in Python is a built-in data type that is similar to a set but with one key difference that is
immutability. This means that once a frozenset is created, we cannot modify its elements that is we
cannot add, remove or change any items in it. Like regular sets, a frozenset cannot contain duplicate
elements.

If no parameters are passed, it returns an empty frozenset.

# Creating a frozenset from a list

fset = frozenset([1, 2, 3, 4, 5])

print(fset) # frozenset({1, 2, 3, 4, 5})

# Creating a frozenset from a set

set1 = {3, 1, 4, 1, 5}

fset = frozenset(set1)

print(fset) # frozenset({1, 3, 4, 5})

Typecasting Objects into Sets


Typecasting objects into sets in Python refers to converting various data types into a set. Python
provides the set() constructor to perform this typecasting, allowing us to convert lists, tuples and
strings into sets.

# Typecasting list into set

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

set1 = set(li)

print(set1)

# Typecasting string into set

s = "AllTheBest"

set1 = set(s)

print(set1)

# Typecasting dictionary into set

d = {1: "One", 2: "Two", 3: "Three"}

set1 = set(d)

print(set1)

Advantages of Set in Python

 Unique Elements: Sets can only contain unique elements, so they can be useful for removing
duplicates from a collection of data.
 Fast Membership Testing: Sets are optimized for fast membership testing, so they can be
useful for determining whether a value is in a collection or not.
 Mathematical Set Operations: Sets support mathematical set operations like union,
intersection and difference, which can be useful for working with sets of data.
 Mutable: Sets are mutable, which means that you can add or remove elements from a set
after it has been created.

Disadvantages of Sets in Python

 Unordered: Sets are unordered, which means that you cannot rely on the order of the data
in the set. This can make it difficult to access or process data in a specific order.
 Limited Functionality: Sets have limited functionality compared to lists, as they do not
support methods like append() or pop(). This can make it more difficult to modify or
manipulate data stored in a set.
 Memory Usage: Sets can consume more memory than lists, especially for small datasets.
This is because each element in a set requires additional memory to store a hash value.
 Less Commonly Used: Sets are less commonly used than lists and dictionaries in Python,
which means that there may be fewer resources or libraries available for working with them.
This can make it more difficult to find solutions to problems or to get help with debugging.

Overall, sets can be a useful data structure in Python, especially for removing duplicates or for fast
membership testing. However, their lack of ordering and limited functionality can also make them
less versatile than lists or dictionaries, so it is important to carefully consider the advantages and
disadvantages of using sets when deciding which data structure to use in your Python program.
Python Lists Tuples in Python Python Sets
In Python, a list is a built-in Python Tuple is a collection Python set is an unordered
dynamic sized array of objects separated by collection of multiple items
(automatically grows and commas. A tuple is similar to having different datatypes.
shrinks). A list may contain a Python list in terms of In Python, sets are mutable,
mixed type of items, List can indexing, nested objects, and unindexed and do not
contain duplicate items. List repetition but the main contain duplicates. The order
in Python are Mutable. difference between both is of elements in a set is not
Hence, we can modify, Python tuple is immutable preserved and can change.
replace or delete the items. t = (10, 20, 30)
Lists are ordered. It
maintains the order of
elements based on how they
are added. Accessing items
in List can be done directly
using their position (index),
starting from 0.
Using Square Brackets Unlike Python lists, tuples Creating a Set in Python
# List of integers are immutable. Like Lists, In Python, the most basic
a = [1, 2, 3, 4, 5] tuples are ordered and we and efficient method for
# List of strings can access their elements creating a set is using curly
b = ['apple', 'banana', using their index values braces.
'cherry'] We cannot update items to a set1 = {1, 2, 3, 4}
# Mixed data types tuple once it is created.
c = [1, 'hello', 3.14, True] Tuples cannot be appended
or extended.
We cannot remove items
from a tuple once it is
created.
Using list() Constructor Adding Elements to a Set in
a = list((1, 2, 3, 'apple', 4.5)) Python
Accessing List Elements Accessing Values # Creating a set
# Access first element print("Value in t[0] = ", t[0]) set1 = {1, 2, 3}
print(a[0 print("Value in t[1] = ", t[1]) # Add one item
# Access last element print("Value in t[-1] = ", t[-1]) set1.add(4)
print(a[-1]) print("Value in t[-2] = ", t[-2]) # Add multiple items
set1.update([5, 6])
Adding Elements into List Concatenation of Python Accessing a Set in Python
•append(): Adds an element Tuples We can loop through a set to
at the end of the list. To Concatenation of Python access set items as set is
•extend(): Adds multiple Tuples, we will use plus unindexed and do not
elements to the end of the operators (+). support accessing elements
list. t1 = (0, 1, 2, 3) by indexing. Also we can use
•insert(): Adds an element at t2 = ('hai', 'welcome') in keyword which is
a specific position. print(t1 + t2) membership operator to
Output check if an item exists in a
(0, 1, 2, 3, 'hai', 'welcome') set.
Removing Elements from List Nesting of Python Tuples set1 = set(["welcome", "to ",
•remove(): Removes the first t1 = (0, 1, 2, 3) "hindustan."])
occurrence of an element. t2 = ('hai', 'welcome') # Accessing element using
•pop(): Removes the t3 = (t1, t2) For loop
element at a specific index or print(t3) for i in set1:
the last element if no index Output print(i, end=" ") # welcome
is specified. ((0, 1, 2, 3), ('hai', to Hindustan.
•del statement: Deletes an 'welcome')) # Checking the element
element at a specified index. # using in keyword
print("to" in set1) # True
Slicing Tuples in Python Removing Elements from the
print(t[1:]) Set in Python
print(t[::-1]) Using remove() Method or
print(t[2:4]) discard() Method
Using pop() Method
Using clear() Method
Deleting a Tuple in Python
del t
Finding the Length of a
Python Tuple
print(len(t))
Assignment Operators in Python

The Python Operators are used to perform operations on values and variables. These are the special
symbols that carry out arithmetic, logical, and bitwise computations. The value the operator
operates on is known as the Operand.

Assignment Operators are used to assign values to variables. This operator is used to assign the
value of the right side of the expression to the left side operand.

# assigning values using # Assignment Operator

a=3

b=5

c=a+b

print(c)

Addition Assignment Operator

The Addition Assignment Operator is used to add the right-hand side operand with the left-hand
side operand and then assigning the result to the left operand.

a=3

b=5

#a=a+b

a += b

print(a)

Subtraction Assignment Operator

The Subtraction Assignment Operator is used to subtract the right-hand side operand from the left-
hand side operand and then assigning the result to the left-hand side operand.

a=3

b=5

#a=a-b

a -= b

print(a)

Multiplication Assignment Operator

The Multiplication Assignment Operator is used to multiply the right-hand side operand with the
left-hand side operand and then assigning the result to the left-hand side operand.
a=3

b=5

#a=a*b

a *= b

print(a)

Division Assignment Operator

The Division Assignment Operator is used to divide the left-hand side operand with the right-hand
side operand and then assigning the result to the left operand.

a=3

b=5

#a=a/b

a /= b

print(a)

Modulus Assignment Operator

The Modulus Assignment Operator is used to take the modulus, that is, it first divides the operands
and then takes the remainder and assigns it to the left operand.

a=3

b=5

#a=a%b

a %= b

print(a)

Floor Division Assignment Operator

The Floor Division Assignment Operator is used to divide the left operand with the right operand and
then assigns the result (floor value) to the left operand.

a=3

b=5

# a = a // b

a //= b

print(a)
Exponentiation Assignment Operator

The Exponentiation Assignment Operator is used to calculate the exponent (raise power) value using
operands and then assigning the result to the left operand.

a=3

b=5

# a = a ** b

a **= b

print(a)

Bitwise AND Assignment Operator

The Bitwise AND Assignment Operator is used to perform Bitwise AND operation on both operands
and then assigning the result to the left operand.

a=3

b=5

#a=a&b

a &= b

# Output

print(a)

Bitwise OR Assignment Operator

The Bitwise OR Assignment Operator is used to perform Bitwise OR operation on the operands and
then assigning result to the left operand.

a=3

b=5

#a=a|b

a |= b

# Output

print(a)

Bitwise XOR Assignment Operator

The Bitwise XOR Assignment Operator is used to perform Bitwise XOR operation on the operands
and then assigning result to the left operand.
a=3

b=5

#a=a^b

a ^= b

# Output

print(a)

Bitwise Right Shift Assignment Operator

The Bitwise Right Shift Assignment Operator is used to perform Bitwise Right Shift Operation on the
operands and then assign result to the left operand.

a=3

b=5

# a = a >> b

a >>= b

# Output

print(a)

Bitwise Left Shift Assignment Operator

The Bitwise Left Shift Assignment Operator is used to perform Bitwise Left Shift Opertator on the
operands and then assign result to the left operand.

a=3

b=5

# a = a << b

a <<= b

# Output

print(a)
Python Bitwise Operators

Python bitwise operators are used to perform bitwise calculations on integers. The integers are first
converted into binary and then operations are performed on each bit or corresponding pair of bits,
hence the name bitwise operators. The result is then returned in decimal format.

Note: Python bitwise operators work only on integers.

Operator Description Syntax


& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

Bitwise AND Operator

Python Bitwise AND (&) operator takes two equal-length bit patterns as parameters. The two-bit
integers are compared. If the bits in the compared positions of the bit patterns are 1, then the
resulting bit is 1. If not, it is 0.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of
both X & y

Note: Here, (111)2 represent binary number.

a = 10

b=4

# Print bitwise AND operation

print("a & b =", a & b)

Bitwise OR Operator

The Python Bitwise OR (|) Operator takes two equivalent length bit designs as boundaries; if the two
bits in the looked-at position are 0, the next bit is zero. If not, it is 1.
Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise OR of
both X, Y

a = 10

b=4

# Print bitwise OR operation

print("a | b =", a | b)

Bitwise XOR Operator

The Python Bitwise XOR (^) Operator also known as the exclusive OR operator, is used to perform
the XOR operation on two operands. XOR stands for “exclusive or”, and it returns true if and only if
exactly one of the operands is true. In the context of bitwise operations, it compares corresponding
bits of two operands. If the bits are different, it returns 1; otherwise, it returns 0.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of
both X & Y

a = 10

b=4

# print bitwise XOR operation

print("a ^ b =", a ^ b)

Bitwise NOT Operator

The preceding three bitwise operators are binary operators, necessitating two operands to function.
However, unlike the others, this operator operates with only one operand.
Python Bitwise Not (~) Operator works with a single value and returns its one’s complement. This
means it toggles all bits in the value, transforming 0 bits to 1 and 1 bits to 0, resulting in the one’s
complement of the binary number.

Example: Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise NOT of X.

a = 10

b=4

# Print bitwise NOT operation

print("~a =", ~a)

Bitwise Shift

These operators are used to shift the bits of a number left or right thereby multiplying or dividing
the number by two respectively. They can be used when we have to multiply or divide a number by
two.

Bitwise Right Shift

Shifts the bits of the number to the right and fills 0 on voids left (fills 1 in the case of a negative
number) as a result. Similar effect as of dividing the number with some power of two.

Example 1:

a = 10 = 0000 1010 (Binary)

a >> 1 = 0000 0101 = 5

Example 2:

a = -10 = 1111 0110 (Binary)

a >> 1 = 1111 1011 = -5

a = 10

b = -10

# print bitwise right shift operator

print("a >> 1 =", a >> 1)

print("b >> 1 =", b >> 1)


Bitwise Operator Overloading

Operator Overloading means giving extended meaning beyond their predefined operational
meaning. For example operator + is used to add two integers as well as join two strings and merge
two lists. It is achievable because the ‘+’ operator is overloaded by int class and str class. You might
have noticed that the same built-in operator or function shows different behavior for objects of
different classes, this is called Operator Overloading.

Application of Bitwise Operators:

Bitwise operators are commonly used in various scenarios, including:

Setting or clearing specific bits within binary data.

Checking the status of flags or bit fields.

Extracting or packing values from or into binary data structures.

Performing arithmetic operations in a more optimized way when dealing with low-level
programming, such as manipulating hardware registers or implementing cryptographic algorithms.

Important points about Bitwise Operators:

Bitwise operators work at the binary level, which is the lowest level of data representation in
computers.

They are typically used in scenarios where fine-grained control over individual bits is necessary, such
as low-level programming, cryptography, and hardware interfacing.

Understanding bitwise operations is crucial for writing efficient code and implementing certain
algorithms.

Sample program for implementation of Bitwise Operator

num1 = 10 # Binary representation: 1010

num2 = 5 # Binary representation: 0101

# Bitwise AND (&)

result_and = num1 & num2 # Result: 0000 (decimal 0)

print("Bitwise AND:", result_and)


# Bitwise OR (|)

result_or = num1 | num2 # Result: 1111 (decimal 15)

print("Bitwise OR:", result_or)

# Bitwise XOR (^)

result_xor = num1 ^ num2 # Result: 1111 (decimal 15)

print("Bitwise XOR:", result_xor)

# Bitwise NOT (~) - Unary operator

result_not1 = ~num1 # Result: 1111 0101 (decimal -11 in 2's complement)

print("Bitwise NOT (num1):", result_not1)

result_not2 = ~num2 # Result: 1111 1010 (decimal -6 in 2's complement)

print("Bitwise NOT (num2):", result_not2)

# Bitwise Left Shift (<<)

result_left_shift = num1 << 1 # Result: 10100 (decimal 20)

print("Bitwise Left Shift:", result_left_shift)

# Bitwise Right Shift (>>)

result_right_shift = num1 >> 1 # Result: 0101 (decimal 5)

print("Bitwise Right Shift:", result_right_shift)


Lab programs

Python String, Lists, Sets, Bit-wise


operators, Assignment operators
Lab Practice Program -12
Python Strings
s = “ABC"
print(s[1]) # access 2nd char(output is ‘B’)
s1 = s + s[0] # update
print(s1) # (output is ‘ABCA’)
# multiline string
ss = """I am in second
year at Hindustan"""
print(ss)
si = “LITERATURE"
print(si[0]) #ouput=L
print(si[4]) #output=R
print(si[-10])
print(si[-5])
sl = “ALLTHEBEST"
print(sl[1:4]) # Retrieves characters from index 1 to 3: ‘LLT'
print(sl[:3]) # Retrieves characters from beginning to index 2: ‘ALL'
print(sl[3:]) # Retrieves characters from index 3 to the end: ‘THEBEST'
print(sl[::-1]) # Reverse a string #output is ‘TSEBEHTLLA’
Lab Practice Program -13
Python Strings Immutability
sg = “LOVEINDIA“
# to change the first character in the string
sg1 = “I" + sg[0:] # create a new string
print(sg1) #output is ‘ILOVEINDIA’
print(len(sg1))
sh = "hello Alice“
sh1 = "H" + sh[1:] # Update- “h” by “H”
print(sh1)
sh2= sh1.replace(“Alice", “Varun") # replace “Alice" with “Varun"
print(sh2) # output “Hello Varun”
print(sh2.upper())
print(sh2.lower())
print(sh2.replace(“Hello", “Welcome"))
print(sh2 * 3)
print(“COM" in sh2)
print(“XYZ" in sh2)
Lab Practice Program -14
Python Lists
#create list
a = [1, 2, 3, 4, 5]
b = ['apple', 'banana', 'cherry']
c = [1, 'hello', 3.14, 20, True]
d = list((5, 4, ‘orange', 4.5))
print(a[0]) # access first item from list a
b.append(11) # add item from list b
c.remove(20) # remove item from list c
print(a)
print(b)
print(c)
print(d)
#Add Elements into List
a.append(10)
print(a)
# Inserting 5 at index 0
a.insert(0, 5)
print(a)
# Adding multiple elements at the end
d.extend([15, 20, 25])
print(d)
#change the value of an element by accessing it using its index
x = [10, 20, 30, 40, 50]
# Change the second element
x[1] = 25
print(x)
Python Lists
# Removing Elements from List
a = [10, 20, 30, 40, 50,50]
# Removes the first occurrence of 30
a.remove(30)
print(a)
# Removes the element at index 1
popped_val = a.pop(1)
print("Popped element:", popped_val)
print(a)
# Deletes the first element (10)
del a[0]
print("After del a[0]:", a)
# Iterating Over Lists
y = ['apple', 'banana', 'cherry']
# Iterating over the list
for item in y:
print(item)
Lab Practice Program -15
a=8
Program for assignment operators
b=5
Find output of the following codes
a += b
a -= b
a *= b
a /= b
a %= b
a **= b
a &= b
a |= b
a ^= b
a >>= b
a <<= b
Lab Practice Program -16
Program for implementation of Bitwise Operator
num1 = 10 # Binary representation: 1010
num2 = 5 # Binary representation: 0101

# Bitwise AND (&)


result_and = num1 & num2
print("Bitwise AND:", result_and)

# Bitwise OR (|)
result_or = num1 | num2
print("Bitwise OR:", result_or)

# Bitwise XOR (^)


result_xor = num1 ^ num2
print("Bitwise XOR:", result_xor)

# Bitwise NOT (~) - Unary operator


result_not1 = ~num1
print("Bitwise NOT (num1):", result_not1)

result_not2 = ~num2
print("Bitwise NOT (num2):", result_not2)

# Bitwise Left Shift (<<)


result_left_shift = num1 << 1
print("Bitwise Left Shift:", result_left_shift)

# Bitwise Right Shift (>>)


result_right_shift = num1 >> 1
print("Bitwise Right Shift:", result_right_shift)
Lab Practice Program -17
Adding Elements to a Set in Python
# Creating a set
set1 = {1, 2, 3}
# Add one item
set1.add(4)
# Add multiple items
set1.update([5, 6])
print(set1)
Lab Practice Program -18
Accessing a Set in Python
set1 = set(["welcome", "to ", "hindustan."])
# Accessing element using For loop
for i in set1:
print(i, end=" ")
# Checking the element
# using in keyword
print(“for" in set1)
Lab Practice Program -19
Removing Elements from the Set in Python
# Using Remove Method
set1 = {1, 2, 3, 4, 5}
set1.remove(3)
print(set1)
# Using discard() Method
set1.discard(4)
print(set1)
# Attempting to discard an element that does not
exist
set1.discard(10) # No error raised
print(set1) # {1, 2, 5}
Lab Practice Program -20
Python program to count the number of
characters in a String

s = “All is Well!“
# Count the characters using len() function
count = len(s)
print(count)
Lab Practice Program -21
Python program to count the number of spaces
in string

s = "Count the spaces in this string."


# Count spaces using the count() method
space_count = s.count(" ")
print(space_count)
Lab Practice Program -22
Python Program to Accept the Strings Which
Contains all Vowels
s = “Aerospace"
v = 'aeiou‘
# check if each vowel exists in the string
if all(i in s.lower() for i in v):
print("True")
else:
print("False")
Lab Practice Program -23
Python Program to Count the Number of
# Sentence
Vowels in a String
string = "Hulkmaniacs are running wild in the whole world“
# Sentence splitted up into words
wordList = string.split()
# Defining vowels for uppercase and lowercase
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
#Traversing every word in wordList
for word in wordList:
vowelCount = 0
#Traversing every character of the word
for i in range(0, len(word)):
# If the word contains a vowel then vowelCount adds by 1
if word[i] in vowels:
vowelCount += 1
print("The word is", word, "and it contains", vowelCount, "vowels in it")
Lab Practice Program -24
Program to find missing numbers
def find_missing_numbers(arr, n):
full_set = set(range(1, n + 1)) # Create a full set of no.s
given_set = set(arr) # Convert the given list into a set
missing_numbers = full_set - given_set # Find the difference
return missing_numbers # Return the missing no.s

arr = [1, 2, 4, 6, 7, 9] # Input list (some numbers missing)


n = 10 # Maximum range value
print(find_missing_numbers(arr, n)) # Output: {3, 5, 8, 10}
Lab Practice Program -25
Program to Remove duplicate characters from a
string
def remove_duplicates(s):
seen = set()
result = []
for char in s:
if char not in seen:
seen.add(char)
result.append(char)
return "".join(result)
print(remove_duplicates("programming"))
# Output: "progamin"

You might also like