Introduction to Data Analytics using Python
Course Code: BBCA403
Semester IV – BCA(VTU)
Handeledby : Saniya
mehdi Module 2 (notes)
Question 1
Explain Python Strings in
detail. Introduction
A string in Python is a sequence of characters enclosed within quotes. It
is used to store textual data such as names, messages, or sentences.
Python allows strings to be written using single quotes (' '), double
quotes (" "), or triple quotes (''' ''' or """ """).
Strings are one of the most commonly used data types in Python because
almost every program processes text in some form.
Creating and Storing Strings
Strings are created simply by assigning text inside quotes to a variable.
Example:
name = "Saniya"
message = 'Welcome to Python'
paragraph = """Python is a powerful programming
language""" print(name)
print(message)
Output:
Saniya
Welcome to Python
Triple quotes allow multi-line strings.
String Immutability
Strings in Python are immutable, which means once a string is created,
its characters cannot be modified.
Example:
text =
"hello"
text[0] =
"h"
This will produce an error because characters cannot be changed
directly. Immutability improves memory efficiency and security.
Accessing Characters Using Index
Characters in a string can be accessed using index
positions. Python indexing starts from 0.
Example:
text =
"Python"
print(text[0]
)
print(text[3]
)
Output:
P
h
Python also supports negative indexing.
Negative indexing starts from the end of
the string.
String Slicing
Slicing is used to extract part of a
string. Syntax:
string[start : stop : step]
Example:
word = "Programming"
print(word[0:6])
print(word[::2])
Output:
Progr
a
Pormi
g
Explanation:
0:6 → extracts characters from index 0 to 5
::2 → prints characters skipping every second character
Escape Sequences
Escape sequences allow special characters inside strings.
Escape Meaning
\n New line
\t Tab space
\\ Backslash
\"
Doubl
e
quote
Single
\' quote
Example:
print("Hello\nWorld")
print("Python\tProgramming")
Output:
Hello
World
Python Programming
Raw Strings
Raw strings ignore escape sequences. They are written using r.
Example:
path = r"C:\Users\Saniya\
Documents" print(path)
Output:
C:\Users\Saniya\Documents
Raw strings are useful when working with file paths and regular
expressions.
String Formatting
String formatting is used to insert values into strings
dynamically. Example using f-strings:
name =
"Saniya" age
= 23
print(f"My name is {name} and I am {age} years old")
Output:
My name is Saniya and I am 23 years old
F-strings are faster and easier to read compared to older formatting
methods.
String Constants
Python provides useful constants through the string
module. Example:
import string
print([Link])
print(string.ascii_lette
rs)
print([Link]
n)
Output:
0123456789
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%C'()*+,-./:;<=>?@[\]^_`{|}~
These constants help in text validation and pattern matching.
Conclusion
Strings are a fundamental data type in Python used for storing and
manipulating textual information. Python provides powerful features such
as indexing, slicing, formatting, escape sequences, and built-in
constants to efficiently process text. Understanding
strings is essential for tasks like data processing, file handling, web
development, and machine learning.
Question 2
Explain important String methods used in Python
with examples. Introduction
Python provides a large number of built-in string methods that simplify
text manipulation. These methods allow programmers to search, modify,
split, join, and validate string data easily. String methods are widely used
in applications such as data cleaning, text processing, and input
validation.
Case Conversion Methods
upper()
Converts all characters to uppercase.
Example:
text =
"python"
print([Link](
))
Output:
PYTHON
lower()
Converts characters to lowercase.
Example:
text =
"HELLO"
print([Link](
))
Output:
hello
strip()
Removes spaces from beginning and end
Example:
text = " Python
"
print([Link](
))
Output:
Python
Searching Methods
find()
Returns the position of a substring.
Example:
text = "Python Programming"
print([Link]("Pro"))
Output:
If the substring is not found, it returns -1.
rfind()
Searches from the right side.
Example:
text = "hello hello"
print([Link]("hello"))
Output:
index()
Similar to find() but raises an error if not
found. Example:
text = "Python"
print([Link]("t"))
Outpu
t: 2
Replace Method
replace()
Replaces a substring with another
value. Example:
text = "I like Java"
print([Link]("Java","Pyth
on")) Output:
I like Python
Split
Methods
split()
Splits a string into a list.
Example:
text = "Python Java C++"
print([Link]())
Output:
['Python', 'Java', 'C++']
rsplit()
Splits from the right side.
Example:
text = "apple,banana,mango"
print([Link](",",1))
Output:
['apple,banana', 'mango']
partition()
Divides a string into three parts.
Example:
text = "Python is easy"
print([Link]("is"))
Output:
('Python ', 'is', ' easy')
Joining
Strings
join()
Combines elements of a list into a single string.
Example:
items = ["Python","Java","C"]
print(", ".join(items))
Output:
Python, Java, C
Validation Methods
These methods check the content of a string.
Example:
text = "Python123"
print([Link]())
print([Link]())
print([Link]())
Output:
Fals
e
Fals
e
True
Explanation:
Method Purpose
isalpha() checks letters
isdigit() checks numbers
isalnum() checks letters + numbers
isspace() checks spaces
Importance of String Methods
String methods are essential for:
Data validation
Cleaning text data
Processing user input
Text formatting
Building search systems
They make Python programs shorter, cleaner, and easier to maintain.
Conclusion
Python string methods provide powerful tools for manipulating text
efficiently. Methods such as upper(), lower(), replace(), split(), join(),
and validation methods help programmers perform complex string
operations with minimal code. These functions are widely used in data
analysis, web development, and natural language processing.
Question 3
Explain Unicode and Encoding in Python
Strings. Introduction
In programming, characters such as letters, numbers, and symbols must
be represented internally using numbers. Unicode is a universal character
encoding standard that assigns a unique number (code point) to every
character used in
languages across the world. Python uses Unicode internally for its string
representation, which allows programs to work with text from different
languages such as English,
Arabic, Hindi, Chinese, etc.
Before Unicode, computers mainly used ASCII (American Standard
Code for
Information Interchange) which supported only 128 characters
including English letters, digits, and punctuation symbols. However, ASCII
could not represent characters from other languages. Unicode was
introduced to solve this limitation.
ASCII vs Unicode
Feature ASCII Unicode
Character support 128 characters Over 1 million
characters Languages supported Mostly English All
world languages
Encoding size 7 bits Variable (UTF-8, UTF-16, UTF-32)
Example of ASCII values:
A → 65
B → 66
C → 67
Example of Unicode values:
A → U+0041
₹ → U+20B9
^•-●(emoji) → U+1F60A
This shows that Unicode can represent many symbols including emojis
and currency signs.
Unicode in Python Strings
In Python 3, all strings are stored as Unicode by default. This means
Python can directly handle characters from any language.
Example:
text =
"Python"
print(text)
Output:
Python
Example with multilingual text:
text = "Hello नमस्ते "
print(text)
Output:
Hello नमस्ते
Python correctly displays characters from different languages because it
internally uses Unicode.
Encoding
Encoding is the process of converting characters into a sequence of bytes
so that they can be stored or transmitted by computers.
Computers store data in binary format (0 and 1). Therefore, strings must
be converted into bytes before storing in files or sending through
networks.
The most common encoding format used today is UTF-8 (Unicode
Transformation Format-8).
Characteristics of UTF-8:
Variable length encoding
Compatible with ASCII
Efficient memory usage
Supports all Unicode characters
Encoding Strings in Python
Python provides the encode() method to convert a string into bytes.
Example:
text = "Python"
encoded_text = [Link]("utf-8")
print(encoded_text)
Output:
b'Python'
Explanation:
encode() converts the string into byte format.
b indicates that the output is a byte
object. Example with Unicode character:
text = "₹"
print([Link]("utf-8"))
Output:
b'\xe2\x82\xb9'
This shows the binary representation of the rupee symbol.
Decoding
Decoding is the reverse process of encoding. It converts bytes back into
readable text. Python provides the decode() method.
Example:
byte_data = b'Python'
print(byte_data.decode("utf-
8"))
Output:
Pytho
n
Here:
byte_data is converted back into a string.
UTF-8 decoding converts binary data into readable characters.
Handling Different Character Sets
When working with files, APIs, or databases, text may come in different
encoding formats such as:
UTF-8
UTF-16
ISO-8859-1
If encoding is incorrect, Python may produce errors like:
UnicodeDecodeError
Example of correct decoding:
data =
"Hello".encode("utf-8")
print([Link]("utf-
8"))
Output:
Hello
Importance of Unicode and Encoding
Unicode and encoding are important for several reasons:
1. Multilingual Support
Programs can process text from multiple languages.
2. Data Storage
Text files and databases store characters in encoded form.
3. Internet Communication
Web pages, APIs, and emails use UTF-8 encoding.
4. Text Processing Applications
Used in natural language processing, machine learning, and search
engines.
Conclusion
Unicode is a universal character encoding standard that enables
computers to represent text from all languages and symbols. Python
supports Unicode strings by default, making it easier to work with
international text. Encoding converts characters into binary format for
storage and transmission, while decoding converts bytes back
into readable text. Methods like encode() and decode() help Python
handle character encoding efficiently. Understanding Unicode and
encoding is essential for developing applications that process global text
data and work reliably across different systems.
Question 4
Explain Python Lists in detail with
examples. Introduction
A list in Python is an ordered collection of elements that can store
multiple values in a
single variable. Lists are one of the most widely used data structures in
Python because
they allow storing different types of data such as integers, strings, and
even other lists. Lists are mutable, which means their elements can be
modified after creation. They are commonly used in data processing,
machine learning, and application development.
Lists are written using square brackets [ ], and elements inside the list
are separated by commas.
Example:
numbers = [10, 20, 30, 40]
print(numbers)
Output:
[10, 20, 30, 40]
Creating Lists
Lists can contain different types of data.
Example:
data = [10, "Python", 3.14,
True] print(data)
Output:
[10, 'Python', 3.14, True]
Python also allows empty
lists. empty_list = []
Lists can also be created using the list() function.
numbers =
list((1,2,3,4))
print(numbers)
Output:
[1, 2, 3, 4]
Indexing in Lists
Each element in a list has an index position
starting from 0. Example:
numbers = [10, 20, 30, 40]
print(numbers[0])
print(numbers[2])
Output:
10
30
Python also supports negative indexing, which starts
from the end. print(numbers[-1])
Output:
40
List Slicing
Slicing extracts a portion of the list.
Syntax:
list[start : stop : step]
Example:
numbers = [10,20,30,40,50]
print(numbers[1:4])
Output:
[20, 30, 40]
Example with step:
print(numbers[::2])
Output:
[10, 30, 50]
Slicing is useful when selecting specific elements from a list.
List Operations
Python supports several operations on lists.
Concatenation (+)
Combines two lists.
a = [1,2,3]
b = [4,5]
print(a + b)
Output:
[1, 2, 3, 4, 5]
Repetition (*)
Repeats list
elements. a =
[1,2,3]
print(a * 2)
Output:
[1, 2, 3, 1, 2, 3]
Membership (in)
Checks if an element exists in
the list. a = [1,2,3]
print(3 in
a)
Output:
True
Built-in Functions for Lists
Python provides several built-in functions that operate on lists.
Function Description
len() returns number of
elements max() returns largest
element
min() returns smallest element
Function Description
sum() returns total sum
Example:
numbers = [10,20,30]
print(len(numbers))
print(max(numbers))
print(min(numbers))
print(sum(numbers))
Output:
3
30
10
60
List Methods
Lists provide many built-in methods to modify elements.
append()
Adds an element at the end.
numbers = [10,20]
[Link](30)
print(numbers)
Output:
[10, 20, 30]
insert()
Adds element at a specific position.
numbers = [10,20,30]
[Link](1,15)
print(numbers)
Output:
[10, 15, 20, 30]
remove()
Removes a specific value.
numbers = [10,15,20,30]
[Link](20)
print(numbers)
Output:
[10, 15, 30]
pop()
Removes element using
index. numbers = [10,20,30]
[Link]()
print(numbers)
Output:
[10, 15]
sort()
Sorts the list.
data = [50,10,40,20]
[Link]
()
print(dat
a)
Output:
[10, 20, 40, 50]
reverse()
Reverses the order.
data =[10, 20, 40,
50]
[Link]
e()
print(data)
Output:
[50, 40, 20, 10]
Advantages of Lists
1. Can store multiple values in one variable
2. Supports different data types
3. Easy to modify (mutable)
4. Provides many built-in methods
Conclusion
Lists are one of the most powerful and flexible data structures in Python.
They allow storing multiple elements in an ordered format and support
operations such as
indexing, slicing, and modification. Python provides numerous built-in
functions and methods like append(), insert(), remove(), pop(),
sort(), and reverse() to manipulate list data efficiently. Because of their
flexibility and ease of use, lists are widely used in applications such as
data analysis, machine learning, and general programming
tasks.
Question 5
Explain List Comprehension and Nested Lists in Python with
examples. Introduction
In Python, List Comprehension is a concise and powerful way to create
lists. It allows programmers to generate a new list by applying an
expression to each element in an existing iterable such as a list, range,
or string. List comprehension makes the code shorter, readable, and
efficient compared to traditional loops.
A Nested List is a list that contains another list as its element. Nested
lists are often
used to represent matrices, tables, and multidimensional data
structures. They are widely used in applications such as data science,
machine learning, and image processing.
List
Comprehension
Definition
List comprehension is a compact syntax used to create lists using a single
line of code. General syntax:
new_list = [expression for item in iterable]
Example:
numbers = [x for x in range(5)]
print(numbers)
Output:
[0, 1, 2, 3, 4]
Explanation:
The loop runs from 0 to 4, and each value is added to the list.
Equivalent traditional loop:
numbers = []
for x in
range(5):
[Link](x)
print(numbers)
Both programs produce the same result, but list comprehension is
shorter and cleaner.
List Comprehension with
Expression Example: Create a
list of squares.
squares = [x*x for x in
range(6)] print(squares)
Output:
[0, 1, 4, 9, 16, 25]
Explanation:
Each number from the range is multiplied by itself.
List Comprehension with Condition
List comprehension can include conditions.
Syntax:
[expression for item in iterable if condition]
Example: Print only even numbers.
numbers = [x for x in range(10) if x%2==0]
print(numbers)
Output:
[0, 2, 4, 6, 8]
Explanation:
Only numbers divisible by 2 are included.
List Comprehension with
Strings Example:
word = "Python"
letters = [char for char in
word] print(letters)
Output:
['P', 'y', 't', 'h', 'o', 'n']
This converts a string into a list of characters.
Nested
Lists
Definition
A nested list is a list containing one or more lists inside it.
Example:
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(matrix)
Output:
[[1,2,3],[4,5,6],[7,8,9]]
This structure is commonly used to represent a matrix (rows and
columns).
Accessing Elements in Nested Lists
To access elements in nested lists, multiple indexes are used.
Example:
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(matrix[1][2])
Output:
Explanation:
matrix[1] → second row [4,5,6]
matrix[1][2] → third element → 6
Nested List Comprehension
Nested list comprehension is used for creating multi-dimensional
lists. Example: Creating a matrix using comprehension.
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix)
Output:
[[0,0,0],
[0,1,2],
[0,2,4]]
Explanation:
Outer loop controls rows
Inner loop controls columns
i*j multiplies row and column index
Flattening a Nested List
Flattening means converting a nested list into a single list.
Example:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [num for row in matrix for num in row]
print(flat)
Output:
[1,2,3,4,5,6,7,8,9]
Explanation:
row accesses each inner list
num extracts each element
Advantages of List Comprehension
1. Reduces code length
2. Improves readability
3. Faster than traditional loops
4. Useful in data processing and transformation
Applications of Nested Lists
Nested lists are used in:
Matrix representation
Game boards
Image processing
Data tables
Machine learning datasets
Example of matrix addition using nested lists:
A = [[1,2],[3,4]]
B = [[5,6],[7,8]]
result = [[A[i][j] + B[i][j] for j in range(2)] for i in
range(2)] print(result)
Output:
[[6,8],[10,12]]
Conclusion
List comprehension is a powerful Python feature used to create lists
efficiently using compact syntax. It simplifies code by replacing traditional
loops and allows the
inclusion of expressions and conditions. Nested lists, on the other hand,
allow Python to store multi-dimensional data such as matrices and
tables. Together, list
comprehension and nested lists play an important role in data analysis,
machine learning, and complex data processing tasks.
Question 6
Explain Shallow Copy and Deep Copy in Python Lists with
examples. Introduction
In Python, copying a list means creating another list that contains the
same elements as the original list. However, copying can be done in two
different ways: Shallow Copy and Deep Copy. Understanding the
difference between these two is very important because incorrect copying
can lead to unexpected changes in the data.
Python lists are mutable, meaning their elements can be modified after
creation. Because of this property, when copying lists, Python may either
copy the references of objects or create completely new objects in
memory. These two approaches are known as shallow copy and deep
copy.
Shallow
Copy
Definition
A shallow copy creates a new list but does not create copies of the
nested objects inside it. Instead, it copies the references of those
objects.
This means that both lists refer to the same nested objects in memory. If
the nested object is modified, the change will appear in both lists.
Example of Shallow Copy
import copy
list1 = [[1,2,3],[4,5,6]]
list2 =
[Link](list1)
list2[0][0] = 100
print("Original List:",
list1) print("Copied
List:", list2)
Output:
Original List: [[100, 2, 3], [4, 5, 6]]
Copied List: [[100, 2, 3], [4, 5, 6]]
Explanation:
[Link]() creates a new outer list.
But inner lists are shared between both lists.
When we changed list2[0][0], it also changed in list1.
This happens because both lists refer to the same nested objects.
Other Ways to Create Shallow Copy
1. Using
slicing list2 =
list1[:]
2. Using list()
function list2 =
list(list1)
3. Using copy()
method list2 =
[Link]()
All these methods create shallow copies.
Deep Copy
Definition
A deep copy creates a completely independent copy of the list and all
the nested objects inside it. Every object is duplicated and stored
separately in memory.
This means modifying one list will not affect the other list.
Example of Deep Copy
import copy
list1 = [[1,2,3],[4,5,6]]
list2 = [Link](list1)
list2[0][0] = 100
print("Original List:",
list1) print("Copied
List:", list2)
Output:
Original List: [[1, 2, 3], [4, 5, 6]]
Copied List: [[100, 2, 3], [4, 5, 6]]
Explanation:
deepcopy() creates copies of all nested objects.
Modifying list2 does not change list1.
This ensures complete independence between the two lists.
Memory
Representation
Shallow Copy
list1 → [A,B]
↓
same objects
list2 → [A,B]
Both lists point to the same inner objects.
Deep Copy
list1 → [A,B]
list2 → [A',B']
New objects are created for the copied list.
When to Use Shallow Copy
Shallow copy is useful when:
Lists contain simple elements (numbers, strings)
Nested objects do not need modification
Memory efficiency is important
Example:
a = [1,2,3]
b = [Link]()
When to Use Deep Copy
Deep copy is useful when:
Lists contain nested structures
Independent modification is required
Data integrity must be maintained
Example:
import copy
b = [Link](a)
Advantages and Disadvantages
Feature Shallow Deep Copy
Copy
Speed Faster Slower
Memory Less More
usage memory memory
Nested Shared Independen
objects t
Safety Less safe Safer
Practical Applications
Shallow and deep copies are used in:
Data processing
Machine learning datasets
Game development
Database record manipulation
Backup and undo systems
For example, when working with large datasets, shallow copy may
improve performance, but deep copy is safer when modifying complex
structures.
Conclusion
Copying lists in Python can be done using shallow copy or deep copy,
depending on the requirements. A shallow copy creates a new list but
shares references to nested objects, while a deep copy creates a
completely independent duplicate of the original list and all its elements.
Understanding the difference between these two methods
helps programmers avoid unexpected modifications and ensures
proper memory management when working with complex data
structures.
Question 7
Explain different techniques for iterating and processing lists in
Python. Introduction
Iteration means accessing each element of a list one by one to perform
some operation.
Python provides several powerful techniques for iterating and processing
lists
efficiently. These techniques help make programs more readable, shorter,
and faster.
Some commonly used list iteration methods include enumerate(), zip(),
reversed(), map(), filter(), and reduce(). These functions allow
programmers to perform operations on lists in a concise and effective
manner.
Using enumerate()
The enumerate() function is used when both the index and the value
of elements are required during iteration.
Syntax:
enumerate(iterable, start=0)
Example:
fruits = ["apple","banana","mango"]
for index, value in enumerate(fruits):
print(index, value)
Output:
0apple
1banana
2mango
Explanation:
enumerate() automatically assigns an index to each element.
It eliminates the need for manual index
counters. Example with starting index:
for i, fruit in enumerate(fruits,
start=1): print(i, fruit)
Output:
1apple
2banana
3mango
Using zip()
The zip() function combines multiple lists into a single iterable.
Example:
numbers =
[1,2,3] letters
= ['a','b','c']
result =
list(zip(numbers,letters))
print(result)
Output:
[(1,'a'), (2,'b'), (3,'c')]
Explanation:
Elements from both lists are paired together.
The result is a list of tuples.
Example using loop:
for num, letter in zip(numbers,letters):
print(num, letter)
Output:
1a
2b
3c
This method is useful when processing multiple lists simultaneously.
Using reversed()
The reversed() function is used to iterate over a list in
reverse order. Example:
numbers = [1,2,3,4]
for num in
reversed(numbers):
print(num)
Output:
4
3
2
1
Explanation:
reversed() returns a reverse iterator.
It does not modify the
original list. Another way to
reverse lists is slicing:
print(numbers[::-1])
Output:
[4,3,2,1]
Using map()
The map() function applies a given function to each element of
an iterable. Syntax:
map(function, iterable)
Example:
numbers = [1,2,3,4]
squares = list(map(lambda x: x*x,
numbers)) print(squares)
Output:
[1,4,9,16]
Explanation:
The lambda function squares each number.
map() applies the function to every element.
Using filter()
The filter() function selects elements from a list based on a condition.
Example:
numbers = [1,2,3,4,5]
even = list(filter(lambda x: x%2==0,
numbers)) print(even)
Output:
[2,4]
Explanation:
The lambda function checks whether numbers are even.
Only elements satisfying the condition are returned.
Using reduce()
The reduce() function performs cumulative operations on list
elements. It is available in the functools module.
Example:
from functools import reduce
numbers = [1,2,3,4]
total = reduce(lambda x,y: x+y,
numbers) print(total)
Output:
10
Explanation:
reduce() repeatedly applies the function to combine elements.
It is useful for operations like sum, product, and aggregation.
Advantages of These Iteration Techniques
1. Reduce code complexity
2. Improve readability
3. Enable functional programming
4. Improve efficiency when processing large datasets
Applications
These techniques are widely used in:
Data analysis
Machine learning preprocessing
Web data processing
Numerical computations
Data transformation pipelines
Example combining functions:
numbers = [1,2,3,4,5]
result = list(map(lambda x:x*x, filter(lambda x:x
%2==0,numbers))) print(result)
Output:
[4,16]
Explanation:
First filter() selects even numbers.
Then map() squares them.
Conclusion
Python provides several powerful techniques for iterating and processing
lists
efficiently. Functions such as enumerate(), zip(), reversed(), map(),
filter(), and reduce() simplify iteration and allow programmers to
perform complex operations with minimal code. These techniques improve
readability, reduce errors, and make programs more efficient. They are
widely used in modern Python applications including data
analysis, machine learning, and software development.
Question 8
Explain Tuples in Python with suitable
examples. Introduction
A tuple in Python is an ordered collection of elements similar to a list, but
unlike lists, tuples are immutable, meaning their elements cannot be
changed after creation.
Tuples are used to store multiple values in a single variable and are
commonly used when the data should remain constant throughout the
program.
Tuples are written using parentheses ( ), and elements are separated by
commas. Because tuples are immutable, they provide better performance
and data security compared to lists.
Example:
t = (10, 20, 30)
print(t)
Output:
(10, 20,
30)
Creating Tuples
Tuples can be created in several ways.
Example 1: Using parentheses
t = (1, 2, 3, 4)
print(t)
Output:
(1, 2, 3, 4)
Example 2: Without parentheses
t = 10, 20, 30
print(t)
Output:
(10, 20, 30)
Python automatically treats comma-separated values as a tuple.
Single Element Tuple
To create a tuple with a single element, a comma is
required. Example:
t = (5,)
print(type(t))
Output:
<class 'tuple'>
Without the comma, Python treats it as an integer instead of a tuple.
Tuple Immutability
Tuples cannot be modified after creation.
Example:
t = (1,2,3)
t[0] = 10
This produces an error because tuples do not allow modification.
Output:
TypeError: 'tuple' object does not support item assignment
However, if a tuple contains a mutable object like a list, that object can still
be modified.
Example:
t = (1, [2,3], 4)
t[1][0] = 10
print(t)
Output:
(1, [10, 3], 4)
Accessing Tuple Elements
Tuple elements are accessed using indexing.
Example:
t = (10,20,30,40)
print(t[0])
print(t[2])
Output:
10
30
Negative indexing is also supported.
Example:
print(t[-
1])
Output:
40
Tuple Packing and
Unpacking Tuple Packing
Packing means storing multiple values into a tuple.
Example:
person = ("John", 25,
"Engineer") print(person)
Output:
('John', 25, 'Engineer')
Tuple Unpacking
Unpacking means extracting values from a tuple into separate variables.
Example:
name, age, job = person
print(name)
print(age)
print(job)
Output:
Joh
n
25
Engineer
This feature makes tuples very useful when returning multiple values from
a function.
Tuple Methods
Tuples have only two built-in methods.
count()
Counts occurrences of an element.
Example:
t = (1,2,3,2,2)
print([Link](2))
Output:
index()
Returns the index of the first occurrence.
Example:
t = (10,20,30)
print([Link](20))
Output:
Nested Tuples
A tuple can contain another tuple.
Example:
t = (1,(2,3),(4,5))
print(t[1])
print(t[1][0])
Output:
(2,3)
2
Nested tuples are useful for representing structured data.
Tuple Concatenation and Repetition
Concatenation:
t1 = (1,2)
t2 = (3,4)
print(t1 + t2)
Output:
(1,2,3,4)
Repetitio
n:
print(t1 *
2)
Output:
(1,2,1,2)
Advantages of Tuples
1. Faster than lists
2. Immutable (data cannot be changed accidentally)
3. Can be used as dictionary keys
4. Less memory usage
When to Use Tuples
Tuples are useful when:
Data should not change
Representing fixed collections (coordinates, database records)
Returning multiple values from functions
Example:
def get_coordinates():
return (10,20)
x,y =
get_coordinates()
print(x,y)
Output:
10 20
Conclusion
Tuples are an important data structure in Python used for storing ordered
collections of elements that should remain unchanged. They support
features such as indexing, unpacking, concatenation, and nesting,
while providing better performance and memory efficiency than lists.
Because of their immutability, tuples are widely used in applications where
data integrity is important, such as database records, coordinates, and
function return values.
Question G
Explain Sets in Python and their operations with
examples. Introduction
A set in Python is an unordered collection of unique elements. Sets are
used to store
multiple items in a single variable, similar to lists and tuples. However,
sets have two important characteristics: they do not allow duplicate
elements, and they do not maintain any specific order.
Sets are written using curly braces { } or the set() function. They are
widely used in applications where we need to perform mathematical set
operations such as union, intersection, and difference.
Example:
numbers = {1,2,3,4}
print(numbers)
Output:
{1, 2, 3, 4}
Since sets are unordered, the output order may vary.
Creating Sets
Sets can be created in different ways.
Using Curly Braces
fruits = {"apple", "banana",
"mango"} print(fruits)
Output:
{'apple', 'banana', 'mango'}
Using set() Function
numbers = set([1,2,3,4])
print(numbers)
Output:
{1, 2, 3, 4}
Removing Duplicates Using Sets
One important property of sets is that they automatically remove
duplicates.
Example:
data = {1,2,2,3,3,4}
print(data)
Output:
{1,2,3,4}
This feature makes sets useful for data cleaning and removing
duplicate values.
Accessing Set Elements
Unlike lists or tuples, sets do not support indexing because they are
unordered. However, elements can be accessed using loops.
Example:
fruits = {"apple","banana","mango"}
for fruit in
fruits:
print(fruit)
Output (order may vary):
apple
banan
a
mang
o
Adding Elements to
Sets add()
Adds a single element.
numbers = {1,2,3}
[Link](4)
print(numbers)
Output:
{1,2,3,4}
update()
Adds multiple elements.
[Link]([5,6])
print(numbers)
Output:
{1,2,3,4,5,6}
Removing Elements
from Sets remove()
Removes a specific element.
numbers = {1,2,3}
[Link](2)
print(numbers)
Output:
{1,3}
If the element does not exist, remove() produces an error.
discard()
Removes an element without producing an error.
[Link](5)
pop()
Removes a random element.
numbers = {1,2,3}
[Link]()
print(numbers)
Output may vary because sets are unordered.
clear()
Removes all elements.
[Link](
)
print(numbers
)
Output:
set()
Set Operations
Python sets support mathematical set operations.
Union
Combines elements of two sets.
A = {1,2,3}
B = {3,4,5}
print([Link](B))
Output:
{1,2,3,4,5}
Operator form:
A|B
Intersection
Returns common
elements.
print([Link](B))
Output:
{3}
Operator:
ACB
Difference
Returns elements present in one set but not in the
other. print([Link](B))
Output:
{1,2}
Operator:
A-B
Symmetric Difference
Returns elements present in either set but not both.
print(A.symmetric_difference(B))
Output:
{1,2,4,5}
Operator:
A^B
Set Comparison Operations
Python provides methods to compare sets.
subset()
Checks whether a set is a subset of another.
A = {1,2}
B = {1,2,3,4}
print([Link](B))
Output:
True
superset()
Checks whether a set contains another
set. print([Link](A))
Output:
True
disjoint()
Checks if two sets have no common elements.
A = {1,2}
B = {3,4}
print([Link](B))
Output:
True
Applications of Sets
Sets are commonly used in:
1. Removing duplicate data
2. Database operations
3. Mathematical computations
4. Membership testing
5. Data analysis and machine learning
Example:
list_data = [1,2,2,3,3,4]
unique =
set(list_data)
print(unique)
Output:
{1,2,3,4}
Advantages of Sets
Automatically removes duplicates
Faster membership testing
Supports mathematical operations
Efficient for large datasets
Conclusion
Sets are an important data structure in Python used for storing unique
elements and performing mathematical set operations. Unlike lists
and tuples, sets do not maintain order and do not allow duplicate values.
Python provides many built-in methods such as add(), remove(),
discard(), union(), intersection(), and difference() to manipulate sets
efficiently. Because of their ability to eliminate duplicates and perform fast
membership tests, sets are widely used in data analysis, database
operations, and algorithm design.
Question 10
Explain Python Dictionaries and their internal working with
examples. Introduction
A dictionary in Python is an unordered collection of data stored in key–
value pairs. Each key is unique and is used to access its
corresponding value. Dictionaries are widely used when data needs to
be stored in the form of mapping or relationships, such as storing
student information, phone numbers, or product details.
Dictionaries are written using curly braces { }, where each element
consists of a key and a value separated by a colon (:).
Example:
student = {"name":"Saniya", "age":23,
"course":"MCA"} print(student)
Output:
{'name':'Saniya', 'age':23, 'course':'MCA'}
In this example:
"name" is the key
"Saniya" is the value
Characteristics of Dictionaries
1. Keys must be unique
2. Values can be duplicated
3. Keys must be immutable (strings, numbers, tuples)
4. Dictionaries are mutable, meaning elements can be added or
modified.
Example:
data = {"a":1, "b":2, "a":3}
print(data)
Output:
{'a':3, 'b':2}
Explanation:
The second "a" overwrites the first value.
Creating
Dictionaries Using
Curly Braces
person = {"name":"John",
"age":25} print(person)
Using dict() Function
person = dict(name="John", age=25)
print(person)
Output:
{'name':'John', 'age':25}
Using fromkeys()
Creates a dictionary with the same value for
multiple keys. keys = ("a","b","c")
d=
[Link](keys,0)
print(d)
Output:
{'a':0, 'b':0, 'c':0}
Accessing Dictionary Values
Values can be accessed using their keys.
Example:
student = {"name":"Saniya","age":23}
print(student["name"])
Output:
Saniya
Using get()
get() retrieves a value safely without causing an error if the key
does not exist. print([Link]("age"))
Output:
23
If key is missing:
print([Link]("marks"))
Output:
None
Dictionary
Methods keys()
Returns all keys.
student = {"name":"Saniya","age":23}
print([Link]())
Output:
dict_keys(['name','age'])
values()
Returns all values.
print([Link]())
Output:
dict_values(['Saniya',23])
items()
Returns key-value
pairs.
print([Link]()
) Output:
dict_items([('name','Saniya'),('age',23)])
update()
Updates dictionary values.
[Link]({"age":24})
print(student)
Output:
{'name':'Saniya','age':24}
pop()
Removes an element using
its key. [Link]("age")
print(student)
Output:
{'name':'Saniya'}
popitem()
Removes the last inserted
element. [Link]()
Iterating Through
Dictionaries Example:
student = {"name":"Saniya","age":23}
for key,value in
[Link]():
print(key,value)
Output:
name
Saniya age
23
Internal Working of Dictionaries
Python dictionaries are implemented using a hash
table. Hashing Mechanism
When a key-value pair is inserted:
1. Python computes a hash value of the key.
2. The hash determines the memory location.
3. The value is stored in that location.
Example:
Key → Hash Function → Memory Location →
Value Because of hashing, dictionary
operations such as:
insertion
deletion
searching
are performed very
quickly. Time
Complexity Operation
Complexity
Search O(1)
Insert O(1)
Delete O(1)
This makes dictionaries very efficient.
Applications of Dictionaries
Dictionaries are widely used in:
Database records
JSON data processing
Configuration storage
Counting frequency of elements
Machine learning datasets
Example: Counting word frequency
text = "python is easy python is powerful"
words =
[Link]() count
= {}
for word in words:
count[word] = [Link](word,0)+1
print(count)
Output:
{'python':2,'is':2,'easy':1,'powerful':1}
Advantages of Dictionaries
1. Fast data access
2. Flexible data storage
3. Easy key-based retrieval
4. Efficient searching using hashing
Conclusion
A dictionary is a powerful data structure in Python that stores data in key-
value pairs. It allows fast data retrieval and efficient storage using a
hashing mechanism. Python
provides several dictionary methods such as keys(), values(), items(),
update(), and pop() to manipulate data easily. Because of their
efficiency and flexibility, dictionaries are widely used in data
processing, web development, and machine learning
applications.
Question 11
Explain Advanced Dictionary Concepts in Python
with examples. Introduction
Python dictionaries are powerful data structures used to store data in
key–value pairs. Apart from basic dictionary operations, Python provides
several advanced features that improve efficiency and functionality when
handling large datasets. Some important advanced dictionary concepts
include dictionary comprehension, nested
dictionaries, defaultdict, OrderedDict, Counter, and dictionary
merging. These features are widely used in data analysis, web
development, and machine learning applications.
Dictionary Comprehension
Dictionary comprehension is a concise way of creating dictionaries using a
single line of code. It works similarly to list comprehension but generates a
dictionary instead of a
list.
Syntax:
{key_expression : value_expression for item in iterable}
Example:
squares = {x: x*x for x in
range(5)} print(squares)
Output:
{0:0, 1:1, 2:4, 3:9, 4:16}
Explanation:
x becomes the key
x*x becomes the value
Dictionary comprehension can also include conditions.
Example:
even_squares = {x: x*x for x in range(10) if x%2==0}
print(even_squares)
Output:
{0:0, 2:4, 4:16, 6:36, 8:64}
This method reduces code complexity and improves readability.
Nested Dictionaries
A nested dictionary is a dictionary that contains another dictionary as its
value.
Example:
students = {
"Saniya": {"age":23, "course":"MCA"},
"John": {"age":22, "course":"BCA"}
}
print(students["Saniya"]["course"])
Output:
MCA
Explanation:
"Saniya" is the outer key
"course" is the inner key
Nested dictionaries are useful for representing complex structured data,
such as student databases or employee records.
defaultdict
The defaultdict class is available in the collections module. It
automatically assigns a default value if a key does not exist.
Example:
from collections import
defaultdict d =
defaultdict(int)
d["a"] += 1
d["b"] += 1
print(d)
Output:
defaultdict(<class 'int'>, {'a':1, 'b':1})
Explanation:
int provides a default value of 0
The dictionary automatically initializes
missing keys This is very useful when counting
elements.
OrderedDict
In older versions of Python, dictionaries did not maintain insertion order.
The OrderedDict class from the collections module preserves the order
in which elements are inserted.
Example:
from collections import
OrderedDict d = OrderedDict()
d["a"] = 1
d["b"] = 2
d["c"] = 3
print(d)
Output:
OrderedDict([('a',1),('b',2),('c',3)])
Note: From Python 3.7 onward, normal dictionaries also maintain insertion
order.
Counter
The Counter class is another powerful dictionary-like structure in the
collections module. It is used to count the frequency of elements.
Example:
from collections import Counter
data =
["apple","banana","apple","orange","banana","apple"]
count = Counter(data)
print(coun
t) Output:
Counter({'apple':3,'banana':2,'orange':1})
Explanation:
Each element becomes a key
Its frequency becomes the value
Counter is widely used in text analysis and data science.
Merging Dictionaries
Python provides multiple ways to merge dictionaries.
Example:
d1 = {"a":1, "b":2}
d2 = {"c":3, "d":4}
merged = {**d1, **d2}
print(merged)
Output:
{'a':1, 'b':2, 'c':3, 'd':4}
Another method using the | operator (Python 3.G+):
merged = d1 |
d2
print(merged)
Output:
{'a':1, 'b':2, 'c':3, 'd':4}
Merging dictionaries is useful when combining data from multiple sources.
Dictionary View Objects
Dictionary methods such as keys(), values(), and items() return view
objects.
Example:
data = {"a":1, "b":2}
print([Link](
))
print([Link]
s())
print([Link]
())
Output:
dict_keys(['a','b
'])
dict_values([1,
2])
dict_items([('a',1),('b',2)])
These views dynamically reflect dictionary changes.
Applications of Advanced Dictionaries
Advanced dictionary features are used in:
Data processing and analytics
Word frequency analysis
Database records
Configuration management
JSON data handling
Example: Word frequency
program from collections
import Counter
text = "python python data science python"
words = [Link]()
result = Counter(words)
print(result)
Output:
Counter({'python':3,'data':1,'science':1})
Conclusion
Advanced dictionary concepts extend the functionality of basic
dictionaries and make Python more powerful for handling complex data.
Features such as dictionary comprehension, nested dictionaries,
defaultdict, OrderedDict, Counter, and
dictionary merging simplify data manipulation and improve program
efficiency. These structures are widely used in data analysis, machine
learning, and real-world
applications, making them an essential part of Python programming.
Question 12
Explain performance considerations and error handling in Python
data structures. Introduction
Python provides several built-in data structures such as lists, tuples,
sets, and
dictionaries for storing and processing data efficiently. When designing
programs, it is important to understand the performance, memory
usage, and error handling
associated with these structures. Performance considerations include
time complexity, memory management, mutable vs immutable
objects, and selecting
the appropriate data structure. Additionally, Python provides
mechanisms for handling runtime errors using exception handling (try-
except).
Understanding these aspects helps programmers write efficient, reliable,
and optimized programs.
Time Complexity of Data Structures
Time complexity describes the amount of time required to perform
operations such as insertion, deletion, or searching.
List Operations
Operation Time Complexity
Access element
O(1) Append
element O(1)
Insert element
O(n) Delete
element O(n)
Search element
O(n) Example:
numbers = [10,20,30,40]
print(numbers[2])
Accessing an element using an index takes constant time O(1).
Set Operations
Sets are implemented using hash tables, which makes membership
testing very fast.
Operation Time Complexity
Add element O(1)
Remove element
O(1) Membership
check O(1) Example:
numbers = {1,2,3,4}
print(3 in numbers)
Output:
True
This operation is very fast because sets use hashing.
Dictionary Operations
Dictionaries also use hash
tables. Operation Time
Complexity Insert key-
value O(1)
Access value
O(1) Delete key
O(1) Example:
student = {"name":"Sam","age":23}
print(student["name"])
Output:
Sam
Dictionaries are extremely efficient for key-based data retrieval.
Mutable vs Immutable Objects
Another important concept in Python is
mutability. Mutable Objects
Mutable objects can be modified after creation.
Examples:
Lists
Dictionaries
Sets
Example:
numbers = [1,2,3]
numbers[0] = 10
print(number
s)
Output:
[10,2,3]
The list element was modified.
Immutable Objects
Immutable objects cannot be changed after
creation. Examples:
Strings
Tuples
Integer
s Example:
text = "hello"
text[0] = "H"
This produces an error because strings are
immutable. Immutability improves data safety and
performance.
Choosing the Right Data Structure
Selecting the correct data structure improves efficiency.
Data Structure Best Use
List Ordered collection with duplicates
Tuple Fixed data that should not change
Set Unique elements and fast membership
Data Structure Best Use
Dictionary Key-value
mapping Example:
numbers = [1,2,3,3,4]
unique = set(numbers)
print(unique)
Output:
{1,2,3,4}
Sets automatically remove duplicates.
Memory Considerations
Different data structures use different amounts of memory.
Lists use more memory because they allow modifications.
Tuples use less memory because they are immutable.
Sets and dictionaries require additional memory for hashing.
Example:
import sys
list_data = [1,2,3]
tuple_data = (1,2,3)
print([Link](list_data))
print([Link](tuple_data)
)
Usually, tuples require less memory than lists.
Error Handling in Python Data Structures
While working with data structures, several errors may occur.
IndexError
Occurs when accessing an invalid index in a list.
Example:
numbers = [1,2,3]
print(numbers[5])
Error:
IndexError
KeyError
Occurs when accessing a dictionary key that does not exist.
Example:
data = {"a":1,"b":2}
print(data["c
"]) Error:
KeyError
TypeError
Occurs when using incorrect data types.
Example:
numbers = [1,2,3]
numbers["1"
] Error:
TypeError
Try-Except for Safe Access
Python provides try-except blocks to handle runtime errors.
Example:
numbers = [1,2,3]
try:
print(numbers[
5]) except
IndexError:
print("Index does not exist")
Output:
Index does not exist
Example with
dictionary:
student = {"name":"sam"}
try:
print(student["age"])
except KeyError:
print("Key not found")
Output:
Key not found
Error handling prevents program crashes.
Practical Applications
Understanding performance and error handling is important for:
Large dataset processing
Machine learning applications
Web development
Database systems
Data validation
For example, using dictionaries instead of lists can improve search
speed in large datasets.
Conclusion
Performance considerations and error handling play an important role
when working with Python data structures. Concepts such as time
complexity, memory usage, mutability, and choosing the
appropriate data structure help in writing efficient programs. Lists,
tuples, sets, and dictionaries each have unique advantages depending
on the application. Additionally, Python’s exception handling using try-
except ensures that programs can manage runtime errors gracefully.
Understanding these concepts
allows developers to build reliable, optimized, and scalable Python
applications.