DAP_2_module
DAP_2_module
Strings in Python
In Python, a string is a sequence of characters, which can include letters, numbers,
punctuation marks, and spaces.
Strings are one of the most commonly used data types in Python and are immutable,
meaning their contents cannot be changed after creation.
Strings are used to represent text data and support a wide range of operations and
methods for manipulation
Strings can be enclosed in either single quotes (') or double quotes ("). Both are equivalent
in Python, allowing developers to choose based on convenience or to avoid escaping
certain characters.
Triple quotes (''' or """) are used to create multi-line strings, which are useful for storing
paragraphs, documentation strings (docstrings), or formatted text.
print(multi_line)
3. Raw Strings
Raw strings are created by prefixing a string literal with r or R. In raw strings, backslashes (\)
are treated as literal characters and not as escape characters. This is particularly useful for
regular expressions or file paths.
• Use Case: Raw strings are ideal for Windows file paths (e.g., r"C:\Users\Name") or
regex patterns where backslashes are common.
4. String as a Sequence
1. String Concatenation
Concatenation combines two or more strings into a single string. Python supports
concatenation using the + operator or by placing string literals side by side.
• str1 = "Hello"
• str2 = "there"
• Side-by-Side Concatenation: When string literals are placed next to each other
without any operator, Python automatically concatenates them. This is less
common but useful for breaking long strings across lines.
• Note: Concatenation using + creates a new string object, as strings are immutable.
2. The in Operator
The in operator is a Boolean operator that checks if one string (substring) is present within
another string. It returns True if the substring is found, otherwise False.
• if 'pa' in "roopa":
print('Your string does not contain any semicolons.') # Output: Your string does not
contain any semicolons.
• Use Case: The in operator simplifies checks for substrings, such as validating input
or searching for patterns. For :
• t = 'a'
• if t in 'aeiou':
3. String Comparison
Strings can be compared using standard comparison operators (<, >, ==, !=, <=, >=).
Comparisons are based on the ASCII or Unicode values of the characters, performed
character by character from left to right.
name = "Ravindra"
word = "Anil"
if name == "Ravindra":
print(f"Your name, {word}, comes before Ravindra.") # Output: Your name, Anil,
comes before Ravindra.
• How It Works: Python compares the ASCII values of corresponding characters. For ,
Anil < Ravindra is True because the ASCII value of A (65) is less than that of R (82).
4. String Traversal
Traversal involves iterating through each character in a string to perform some action. This
can be done using a for loop or a while loop.
fruit = "grapes"
st = "Roopa"
index = 0
index += 1
5. String Slicing
Explanation:
s = "Python"
print(s[1:4]) # yth
print(s[::-1]) # nohtyP
6. String Repetition
Explanation:
s = "Hi"
print(s * 3) # HiHiHi
7. Finding Substrings
Explanation:
s = "hello world"
print(s.find("world")) # 6
8. Replacing Substrings
Explanation:
s = "bad dog"
print(s.replace("bad", "good")) # good dog
Indexing allows programmers to retrieve specific characters from a string based on their
position.
Python supports both positive indexing (starting from the beginning) and negative
indexing (starting from the end), making it versatile for string manipulation.
This feature is fundamental for tasks such as parsing text, extracting substrings, or
processing individual characters.
1. Concept of Indexing
• Indexing in Python is zero-based, meaning the first character has an index of 0, the
second character has an index of 1, and so on.
• The index value must be an integer (or an expression that evaluates to an integer).
• Python also supports negative indexing, where the last character has an index of -1,
the second-to-last has an index of -2, and so forth.
2. Syntax
To access a character in a string, use square brackets ([]) with the index number:
string_name[index]
3. Positive Indexing
Positive indices are used to access characters from the start of the string. The index starts
at 0 for the first character and increments by 1 for each subsequent character.
• word = "Python"
• Illustration:
s = "good morning"
print(s[0]) # Output: g
print(s[5]) # Output: m
print(s[11]) # Output: g
i=2
4. Negative Indexing
Negative indices allow access to characters from the end of the string. The last character
has an index of -1, the second-to-last has an index of -2, and so on.
word = "Python"
• Illustration:
s = "good morning"
• Use Case: Negative indexing is particularly useful when you need to access
characters relative to the end of a string without knowing its exact length.
5. Error Handling
Attempting to access an index that is out of range (i.e., greater than or equal to the string's
length or less than the negative length) results in an IndexError.
word = "Python"
Prevention: Always ensure the index is within the valid range. You can use the len()
function to check the string's length:
word = "Python"
print(word[5]) # Output: n
else:
6. Applications of Indexing
• Extracting Specific Characters: Retrieve specific characters, such as the first letter
of a name or the last digit of a code.
• Parsing Strings: Process strings character by character, e.g., checking for vowels or
digits.
String slicing allows you to extract a portion (or substring) of a string, while string joining
combines multiple strings into a single string using a separator.
These operations are fundamental for text processing, data parsing, and string formatting
in Python, leveraging the language's flexibility and simplicity.
String Slicing
• Slicing creates a new string containing the selected characters without modifying
the original string (since strings are immutable).
• Slicing is performed using the colon (:) operator within square brackets, allowing you
to specify the start, end, and step (stride) of the slice.
2. Syntax
string_name[start:end:step]
• start: The index where the slice begins (inclusive). If omitted, defaults to 0 (start of
the string).
• end: The index where the slice ends (exclusive). If omitted, defaults to the length of
the string.
• step: The increment between indices (also called stride). If omitted, defaults to 1. A
negative step reverses the direction of the slice.
• The slice includes characters from the start index up to, but not including, the end
index.
• The step determines how indices are incremented (e.g., every character, every
second character, or in reverse).
Index 0 1 2 3 4 5 6 7 8 9
Character a b c d e f g h i j
• Basic Slicing:
• Full String:
• Using Step:
• Reversing a String:
• Immutability: Slicing does not modify the original string; it returns a new string.
• Applications: Slicing is used for tasks like extracting substrings, reversing strings,
skipping characters, or parsing structured text (e.g., extracting a file extension from
a filename).
String Joining
• String joining is the process of concatenating multiple strings into a single string,
typically with a specified separator (delimiter) between each string.
• Joining is the inverse of splitting, where a string is broken into a list of substrings.
2. Syntax
separator.join(iterable)
• separator: The string used to separate the elements (e.g., ", ", "-", or an empty string
• iterable: An iterable (e.g., list, tuple, or string) containing the strings to be joined.
• The join() method takes each element from the iterable, converts it to a string (if
necessary), and concatenates them, inserting the separator between each pair of
elements.
• The result is a single string containing all elements with the separator.
4. s of String Joining
s1 = '-'
s1 = 'abc'
s2 = '123'
Explanation: The string s1 (abc) is inserted between each character of s2 (123), resulting in
1abc2abc3.
result = ''.join(chars)
• Iterable Requirement: The join() method requires an iterable where all elements
can be converted to strings. Non-string elements (e.g., integers) will raise a
TypeError unless converted first.
nums = [1, 2, 3]
String Methods
In Python, strings are immutable sequences of characters that come with a rich set of built-
in methods for manipulation.
These string methods are functions attached to string objects, allowing programmers to
perform operations like modifying case, searching, replacing, splitting, joining, and
formatting strings.
Since strings are objects in Python, these methods are accessed using the dot operator
(e.g., string.method()). This comprehensive guide covers all string methods available in
Python, as listed by the dir(str) function, with detailed explanations and s.
Python provides a wide range of string methods, each designed for specific text-processing
tasks. These methods do not modify the original string (due to immutability) but return a
new string or other data types (e.g., lists, integers, or booleans) based on the operation. The
methods can be explored using the dir() function:
print(dir(stuff))
The methods starting with double underscores (e.g., __add__) are special methods (dunder
methods) that define operator behavior or internal functionality. This guide focuses on the
public string methods (non-dunder methods) used for common string operations.
a. capitalize()
o Description: Returns a copy of the string with the first character capitalized
and the rest in lowercase.
o Syntax: string.capitalize()
o msg = "bengaluru"
b. casefold()
o Syntax: string.casefold()
o first = "india"
o second = "INDIA"
c. lower()
o Syntax: string.lower()
o text = "HeLLo"
d. upper()
o Syntax: string.upper()
o text = "HeLLo"
e. swapcase()
o Syntax: string.swapcase()
o text = "HeLLo"
o Use Case: Creating visual effects or toggling case for specific formatting.
f. title()
o Description: Returns a copy of the string with the first character of each
word capitalized and the rest in lowercase.
o Syntax: string.title()
o Note: May not handle apostrophes correctly (e.g., "it's" becomes "It'S").
o Description: Returns the lowest index where the substring sub is found
within string[start:end]. Returns -1 if not found.
o st = "calender of Feb.cal2019"
o print(st.find('cal')) # Output: 0
print(st.find('x')) # Output: -1
o Description: Like find(), but raises a ValueError if the substring is not found.
o st = "hello"
o print(st.index('l')) # Output: 2
o Use Case: When you expect the substring to exist and want to handle errors
explicitly.
o text = "logical"
o Description: Returns True if the string ends with suffix, False otherwise.
suffix can be a string or tuple of strings.
o text = "hello.txt"
• strip([chars])
o Syntax: string.strip(chars=None)
st = "###Hello###"
• lstrip([chars])
o Description: Removes leading whitespace (or specified chars) from the
string.
o Syntax: string.lstrip(chars=None)
o st = " hello"
o st = "###hello"
• rstrip([chars])
o Syntax: string.rstrip(chars=None)
o st = "hello "
o st = "hello###"
a. split(sep=None, maxsplit=-1)
o Description: Splits the string into a list of substrings based on sep. If sep is
None, splits on whitespace. maxsplit limits the number of splits.
text = "banana"
a. isalnum()
o Syntax: string.isalnum()
b. isalpha()
o Description: Returns True if all characters are letters and the string is non-
empty.
o Syntax: string.isalpha()
o Description: Returns True if all characters are ASCII (code points 0–127).
o Syntax: string.isascii()
d. isdecimal()
o Description: Returns True if all characters are decimal digits (0–9) and the
string is non-empty.
o Syntax: string.isdecimal()
e. isdigit()
o Syntax: string.isdigit()
f. isnumeric()
o Syntax: string.isnumeric()
o Description: Returns True if all cased characters are lowercase and there is
at least one cased character.
o Syntax: string.islower()
h. isupper()
o Description: Returns True if all cased characters are uppercase and there is
at least one cased character.
o Syntax: string.isupper()
i. istitle()
o Description: Returns True if the string is in title case (each word starts with
an uppercase letter, followed by lowercase).
o Syntax: string.istitle()
j. isspace()
o Syntax: string.isspace()
print(dir("hello"))
help(str.capitalize)
String Formatting
String formatting in Python is the process of creating strings by embedding values or
variables into predefined templates.
It allows developers to produce dynamic, readable, and well-structured text output, such
as generating user messages, reports, or formatted data.
Python offers multiple approaches to string formatting, each with its own syntax and use
cases.
These methods are essential for tasks like creating user interfaces, logging, or generating
structured output (e.g., JSON, HTML).
This guide covers all major string formatting techniques in Python, including the %
operator, str.format(), f-strings, and template strings, with detailed explanations and s.
Python provides four primary methods for string formatting, each introduced at different
stages of the language's evolution. These methods are designed to balance simplicity,
flexibility, and performance.
Description
• It is inspired by C's printf function and uses format specifiers (e.g., %s, %d) to define
the type and format of inserted values.
• While still supported, it is considered outdated and less readable compared to
newer methods.
Format Specifiers
• %d or %i: Integer
• %x or %X: Hexadecimal
name = "Alice"
age = 25
score = 95.678
Limitations
• Error-prone with multiple arguments (requires correct order and type matching).
2. str.format() Method
Description
Features
# Positional arguments
# Named arguments
# Formatting numbers
print("Price: ${:.2f}".format(19.999))
# Reusing placeholders
Limitations
Description
• They use the prefix f or F and embed expressions directly inside curly braces {}
within the string.
• f-strings are highly readable and performant, as they are evaluated at runtime.
Features
• Debugging: Since Python 3.8, ={} displays both the expression and its value (e.g.,
f"{x=}").
name = "David"
age = 40
# Expressions
x = 10
# Formatting numbers
price = 29.999
print(f"Price: ${price:.2f}")
y=5
print(f"{y=}")
# Output: y=5
Advantages
Limitations
• Less suitable for templates defined separately from data (e.g., in configuration files).
Advanced Formatting Techniques
1. Nested Formatting
width = 10
text = "hello"
2. Multiline Formatting
• f-strings and Template strings support multiline strings using triple quotes.
name = "Grace"
print(f"""Dear {name},
Lists
In Python, a list is a versatile, mutable, and ordered collection of elements that can store
items of different data types (e.g., integers, strings, or even other lists).
Lists are one of Python's most commonly used data structures due to their flexibility and
ease of manipulation.
They are defined using square brackets [] and support a variety of operations for adding,
removing, and modifying elements.
Lists in Python
Characteristics of Lists
• Ordered: Elements maintain their insertion order, accessible via indices starting
from 0.
• Heterogeneous: Can contain elements of different types (e.g., [1, "hello", 3.14]).
The most common way to create a list is by enclosing elements in square brackets [],
separated by commas.
• numbers = [1, 2, 3, 4, 5]
The list() function can create a list from an iterable (e.g., string, tuple, range) or an empty
list.
3. List Comprehension
zeros = [0] * 5
repeated = ["hello"] * 3
• Use Case: Initializing lists with repeated values (e.g., for counters or placeholders).
Nested
1. Accessing Elements
Elements in a list are accessed using their index, with zero-based indexing. Negative
indices access elements from the end.
• Syntax: list_name[index]
2. Slicing
Slicing extracts a portion of the list using a range of indices, returning a new list.
• Syntax: list_name[start:end:step]
• numbers = [0, 1, 2, 3, 4, 5]
3. Modifying Elements
Lists are mutable, so elements can be changed by assigning new values to specific indices.
• fruits[1] = "mango"
4. Concatenation
• list1 = [1, 2, 3]
• list2 = [4, 5, 6]
• list1 = [1, 2]
• repeated = list1 * 3
6. Membership Testing
The in and not in operators check if an element exists in a list, returning a boolean.
7. Length
• Syntax: len(list_name)
• numbers = [1, 2, 3, 4]
• print(len(numbers)) # Output: 4
print(len([])) # Output: 0
8. Traversal
Indexing allows you to access individual elements in a list using their position, while
slicing enables you to extract a portion of the list as a new list.
These operations are fundamental for working with lists, enabling tasks such as data
extraction, modification, and transformation.
Indexing in Lists
1. Concept of Indexing
• Each element in a list is assigned a unique index, which is an integer representing its
position.
• Python uses zero-based indexing, meaning the first element is at index 0, the
second at index 1, and so on.
• Lists also support negative indexing, where the last element is at index -1, the
second-to-last at -2, and so forth.
• Indexing allows direct access to elements for reading or modification, as lists are
mutable.
2. Syntax
list_name[index]
3. Positive Indexing
Positive indices are used to access elements from the start of the list, beginning at index 0.
• Illustration:
Element 10 20 30 40 50
Index 0 1 2 3 4
print(numbers[1]) # Output: 20
print(numbers[4]) # Output: 50
4. Negative Indexing
Negative indices allow access to elements from the end of the list, with -1 referring to the
last element.
• Illustration:
Element 10 20 30 40 50
Negative Index -5 -4 -3 -2 -1
print(numbers[-1]) # Output: 50
print(numbers[-3]) # Output: 30
• Use Case: Negative indexing is useful for accessing elements relative to the end
without knowing the list's length.
• fruits[1] = "mango"
7. Applications of Indexing
• Data Retrieval: Access specific elements (e.g., first item in a shopping list).
Slicing in Lists
1. Concept of Slicing
• Slicing extracts a portion of a list, returning a new list containing the selected
elements.
• Slicing is performed using a range of indices, specified with colons (:) in the format
start:end:step.
• Slicing is non-destructive, preserving the original list while creating a new one.
2. Syntax
list_name[start:end:step]
• start: The index where the slice begins (inclusive). Defaults to 0 if omitted.
• end: The index where the slice ends (exclusive). Defaults to the list's length if
omitted.
• step: The increment between indices. Defaults to 1. A negative step reverses the
direction.
• The step determines which elements are included (e.g., every element, every
second element, or in reverse).
• Slicing supports both positive and negative indices, making it highly flexible.
4. s of Slicing
Index 0 1 2 3 4 5 6 7
Element 0 1 2 3 4 5 6 7
Negative Index -8 -7 -6 -5 -4 -3 -2 -1
• Basic Slicing:
• Full List:
• Using Step:
• Reversing a List:
Slicing can be used to modify multiple elements at once by assigning a new list to a slice.
The assigned list does not need to have the same length as the slice.
numbers = [0, 1, 2, 3, 4, 5]
These functions are not specific to lists but are frequently used with them due to lists'
iterable and sequence-based nature.
Python's built-in functions that are commonly used with lists operate on iterables or
sequences, making them highly effective for list manipulation. Below is a comprehensive
list of these functions, focusing on their application to lists, with detailed explanations.
1. len()
• Syntax: len(list)
• print(len(fruits)) # Output: 3
• empty = []
print(len(empty)) # Output: 0
2. max()
• Description: Returns the largest element in a list based on comparison. For lists
with mixed types, elements must be comparable.
numbers = [5, 2, 8, 1, 9]
print(max(numbers)) # Output: 9
• Notes:
3. min()
numbers = [5, 2, 8, 1, 9]
print(min(numbers)) # Output: 1
4. sum()
• Description: Returns the sum of all elements in a list. Elements must be numeric
(integers, floats, etc.).
numbers = [1, 2, 3, 4]
print(sum(numbers)) # Output: 10
5. sorted()
• Description: Returns a new sorted list from the elements of the input list. Does not
modify the original list.
numbers = [5, 2, 8, 1, 9]
6. all()
• Description: Returns True if all elements in the list are truthy or if the list is empty.
• Syntax: all(list)
numbers = [1, 2, 3, 4]
• empty = []
• Description: Returns True if at least one element in the list is truthy. Returns False
for an empty list.
• Syntax: any(list)
numbers = [0, 0, 1, 0]
9. zip()
• Description: Combines multiple lists (or iterables) into an iterator of tuples, where
each tuple contains the corresponding elements from each list.
• Syntax: zip(*lists)
print(f"{name}: {score}")
List Methods
These methods are specific to lists and are distinct from built-in functions (e.g., len(),
sorted()) that work with multiple types. The methods can be explored using the dir()
function:
my_list = [1, 2, 3]
print(dir(my_list))
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
The dunder methods (e.g., __add__, __len__) handle internal operations like operators and
are not covered here, as they are not typically called directly. This guide focuses on the 11
public list methods, organized by functionality.
a. append(object)
o Description: Adds a single element (any Python object) to the end of the list.
Modifies the list in place.
o Syntax: list.append(object)
fruits.append("orange")
b. extend(iterable)
o Description: Adds each element from an iterable (e.g., list, tuple, string) to
the end of the list. Modifies the list in place.
o Syntax: list.extend(iterable)
numbers = [1, 2, 3]
numbers.extend([4, 5])
c. insert(index, object)
fruits.insert(1, "mango")
2. Removing Elements
These methods remove elements from a list.
a. pop([index])
o Syntax: list.pop(index=-1)
numbers = [1, 2, 3, 4]
o last = numbers.pop()
o print(last) # Output: 4
b. remove(value)
o Description: Removes the first occurrence of the specified value from the
list. Modifies the list in place.
o Syntax: list.remove(value)
fruits.remove("apple")
c. clear()
o Description: Removes all elements from the list, leaving it empty. Modifies
the list in place.
o Syntax: list.clear()
numbers = [1, 2, 3]
numbers.clear()
print(numbers) # Output: []
o print(fruits.index("banana")) # Output: 1
b. count(value)
o Syntax: list.count(value)
o numbers = [1, 2, 2, 3, 2]
o print(numbers.count(2)) # Output: 3
a. sort(key=None, reverse=False)
o Description: Sorts the list in place, using the Timsort algorithm. The key
function customizes the sort order, and reverse=True sorts in descending
order.
numbers = [5, 2, 8, 1, 9]
numbers.sort()
numbers.sort(reverse=True)
words.sort(key=len)
b. reverse()
o Syntax: list.reverse()
numbers = [1, 2, 3, 4]
o numbers.reverse()
5. Copying Method
a. copy()
o Description: Returns a shallow copy of the list, creating a new list with the
same elements.
o Syntax: list.copy()
o original = [1, 2, 3]
o duplicate = original.copy()
o duplicate.append(4)
Sets in Python
In Python, a set is a built-in data structure that represents an unordered collection of
unique elements.
Sets are highly efficient for operations like membership testing, eliminating duplicates, and
performing mathematical set operations (e.g., union, intersection).
They are mutable (can be modified) but can only contain immutable (hashable) elements,
such as numbers, strings, or tuples.
Sets are particularly useful in scenarios requiring uniqueness and fast lookups.
Characteristics of Sets
• Unordered: Elements in a set have no defined order, and indexing is not supported.
• Iterable: Sets can be looped over, but the order of elements is not guaranteed.
Creating Sets
Sets can be created in several ways, depending on the use case. Below are the primary
methods for creating sets in Python:
A set is created by enclosing elements in curly braces {}, separated by commas. Note that
an empty {} creates a dictionary, not a set.
The set() function creates a set from an iterable (e.g., list, tuple, string) or an empty set.
3. Creating a Frozenset
1. Membership Testing
The in and not in operators check if an element exists in a set, leveraging sets' efficient
hash-based lookup.
2. Iteration
Sets are iterable, allowing traversal using loops, though the order is not guaranteed.
• numbers = {1, 2, 3}
3. Length
• Syntax: len(set)
• print(len(fruits)) # Output: 3
print(len(set())) # Output: 0
• Operators:
o Difference (-): Returns elements in one set but not the other.
o Symmetric Difference (^): Returns elements in either set but not both.
a = {1, 2, 3}
b = {2, 3, 4}
Set Methods
Sets provide a rich set of methods for manipulation, many corresponding to mathematical
operations. Below are the key methods, grouped by functionality:
1. Adding Elements
a. add(elem)
o Description: Adds a single element to the set if it’s not already present.
Modifies the set in place.
fruits.add("orange")
b. update(*others)
o Description: Adds elements from one or more iterables (e.g., lists, sets) to
the set. Modifies the set in place.
numbers = {1, 2}
numbers.update([2, 3, 4])
2. Removing Elements
a. remove(elem)
o Description: Removes the specified element from the set. Raises KeyError if
the element is not found.
fruits.remove("banana")
b. discard(elem)
o Description: Removes the specified element from the set if present. Does
not raise an error if the element is not found.
fruits.discard("banana")
c. pop()
o Description: Removes and returns an arbitrary element from the set. Raises
KeyError if the set is empty.
numbers = {1, 2, 3}
elem = numbers.pop()
d. clear()
fruits.clear()
These methods perform set operations, similar to operators, and can modify the set in
place or return a new set.
a. union(*others) / |
o Description: Returns a new set containing all elements from the set and the
specified iterables.
a = {1, 2}
b = {2, 3}
b. intersection(*others) / &
o Description: Returns a new set with elements common to the set and all
specified iterables.
c. difference(*others) / -
o Description: Returns a new set with elements in the set but not in the
specified iterables.
d. symmetric_difference(other) / ^
o Description: Returns a new set with elements in either the set or the
specified iterable, but not both.
4. Testing Methods
o Description: Returns True if the set is a subset of other (all elements in the
set are in other). < checks for proper subset.
c. isdisjoint(other)
o Description: Returns True if the set has no elements in common with other.
Tuples in Python
In Python, a tuple is a built-in data structure that represents an ordered, immutable
collection of elements.
Tuples are similar to lists but cannot be modified after creation, making them suitable for
storing fixed data.
They can contain elements of any data type, including mixed types, and are highly efficient
for memory usage and performance.
Tuples are widely used for tasks requiring data integrity, such as returning multiple values
from functions or representing fixed collections.
Characteristics of Tuples
• Ordered: Elements maintain their insertion order, accessible via indices starting
from 0.
• Heterogeneous: Can contain elements of different types (e.g., [1, "hello", 3.14]).
Creating Tuples
Tuples can be created in several ways, offering flexibility for different use cases. Below are
the primary methods for creating tuples in Python:
1. Using Parentheses
The most common way to create a tuple is by enclosing elements in parentheses (),
separated by commas. Parentheses are optional for non-empty tuples.
• numbers = (1, 2, 3)
• coords = 10, 20
The tuple() function creates a tuple from an iterable (e.g., list, string, range) or an empty
tuple.
Elements are accessed using zero-based indices, with negative indices for accessing from
the end.
• Syntax: tuple_name[index]
2. Slicing
• Syntax: tuple_name[start:end:step]
• numbers = (0, 1, 2, 3, 4, 5)
3. Concatenation
• tuple1 = (1, 2)
• tuple2 = (3, 4)
4. Repetition
The * operator repeats a tuple a specified number of times, creating a new tuple.
• tuple1 = (1, 2)
• repeated = tuple1 * 3
5. Membership Testing
6. Length
• Syntax: len(tuple)
• numbers = (1, 2, 3)
• print(len(numbers)) # Output: 3
print(len(())) # Output: 0
Tuple Methods
Tuples have only two built-in methods due to their immutability, focusing on searching and
counting elements.
1. count(value)
• numbers = (1, 2, 2, 3, 2)
• print(numbers.count(2)) # Output: 3
print(numbers.count(4)) # Output: 0
• Description: Returns the index of the first occurrence of value in the tuple within
the range start to end. Raises ValueError if not found.
• print(fruits.index("banana")) # Output: 1
# print(fruits.index("grape")) # ValueError
Since tuples are immutable, there are very few methods directly available for them.
However, many built-in functions can operate on tuples.
Function Explanation
Returns the maximum value in the tuple (works if elements are comparable,
max(tuple)
like numbers or strings).
Adds up all the numbers in the tuple (only works if the elements are
sum(tuple)
numbers).
count(x) Tuple method: Returns how many times x appears in the tuple.
index(x) Tuple method: Returns the index of the first occurrence of x in the tuple.
Dictionaries
In Python, a dictionary is a built-in data structure that stores data in key-value pairs,
providing an efficient way to map unique keys to values.
Dictionaries are unordered , mutable, and highly versatile, making them ideal for tasks like
data lookup, configuration storage, and data organization.
Keys must be immutable and hashable (e.g., strings, numbers, tuples), while values can be
of any type.
Characteristics of Dictionaries
• Key-Value Pairs: Each key is associated with a value, forming a mapping (e.g.,
{"name": "Alice", "age": 25}).
• Unique Keys: Keys must be unique; duplicate keys overwrite existing values.
• Hashable Keys: Keys must be immutable (e.g., strings, numbers, tuples with
immutable elements).
• Iterable: Dictionaries can be looped over to access keys, values, or key-value pairs.
Creating Dictionaries
Dictionaries can be created in several ways, offering flexibility for different use cases.
Below are the primary methods for creating dictionaries in Python:
A dictionary is created by enclosing key-value pairs in curly braces {}, with keys and values
separated by colons : and pairs separated by commas.
• empty_dict = {}
print(empty_dict) # Output: {}
The dict() function creates a dictionary from an iterable of key-value pairs, keyword
arguments, or an empty dictionary.
• person = dict(pairs)
• empty_dict = dict()
print(empty_dict) # Output: {}
The zip() function can pair two iterables (e.g., lists) to create a dictionary.
1. Accessing Values
Values are accessed using keys in square brackets [] or the get() method.
o Syntax: dict_name[key]
• Using get():
o print(person.get("age")) # Output: 25
2. Modifying Values
Dictionaries are mutable, so values can be updated or new key-value pairs added using
assignment.
• Using del:
o del person["age"]
• Using pop():
o age = person.pop("age")
o print(age) # Output: 25
4. Membership Testing
5. Length
The len() function returns the number of key-value pairs in the dictionary.
• Syntax: len(dict)
• print(len(person)) # Output: 2
print(len({})) # Output: 0
6. Iteration
• Using keys():
• Using values():
• Using items():
• Use Case: Processing dictionary data (e.g., generating reports or summing values).
Dictionary Methods
Dictionaries provide a variety of built-in methods for manipulation. Below are the key
methods, organized by functionality:
1. Accessing Methods
a. get(key[, default])
o Description: Returns the value for key if it exists; otherwise, returns default
(or None if not specified).
b. keys()
c. values()
d. items()
2. Modifying Methods
• update([other])
print(person) # Output: {'name': 'Bob', 'age': 25, 'city': 'Boston', 'grade': 85}
• setdefault(key[, default])
o Description: Returns the value for key if it exists; otherwise, inserts key with
default value and returns default.
3. Removing Methods
• pop(key[, default])
o Description: Removes and returns the value for key. Returns default if key is
not found, or raises KeyError if no default.
o print(person.pop("age")) # Output: 25
• popitem()
o Description: Removes and returns the last inserted key-value pair as a tuple
(Python 3.7+).
• clear()
o person.clear()
print(person) # Output: {}
4. Copying Method
a. copy()
o duplicate = person.copy()
5. sorts
Purpose Syntax
Function Purpose
Files can be read to retrieve data or written to store data, supporting various formats like
text, CSV, JSON, or binary. Python provides built-in functions and methods to perform
reading and writing operations efficiently, with robust mechanisms for managing file
access and ensuring data integrity.
What is a File?
A file is a named location on a storage device used to store data permanently. Files can
contain text, binary data, or structured formats (e.g., CSV, JSON). Python interacts with files
through file objects, which provide methods for reading, writing, and managing file
operations.
Types of Files
• Text Files: Store human-readable data as strings (e.g., .txt, .csv, .json). Encoded in
formats like UTF-8.
• Binary Files: Store non-text data (e.g., images, audio, executables) in bytes (e.g.,
.jpg, .mp3, .bin).
File Operations
Python uses the built-in open() function to create a file object, which serves as an interface
to the file.
o encoding: Specifies the character encoding for text files (e.g., "utf-8").
Ignored for binary modes.
"r" Read (text, default) File must exist; raises FileNotFoundError if not.
"r+" Read and write (text) File must exist; allows both operations.
"w+" Write and read (text) Creates/overwrites file; allows both operations.
file.close()
• Note: Always close files after use to free resources, typically using close() or a with
statement.
The with statement is the preferred way to handle files, as it automatically closes the file,
even if an error occurs.
• Syntax:
# File operations
• content = file.read()
Reading Files
Reading a file involves retrieving its contents into memory for processing. Python provides
several methods to read text and binary files, with options to read all content, specific
lines, or chunks.
a. read(size=-1)
o content = file.read()
o Use Case: Reading small files or when the entire content is needed.
o Note: For large files, reading the entire content may consume significant
memory.
b. readline(size=-1)
o line1 = file.readline()
o line2 = file.readline()
c. readlines()
o Description: Reads all lines into a list, with each line as a string
Binary files are read in bytes using binary modes ("rb", "r+b"). The methods are similar but
return bytes objects.
• Use Case: Reading non-text files like images, audio, or serialized data.
Error Handling
• try:
• content = file.read()
• except FileNotFoundError:
Writing Files
Writing a file involves storing data into a file, either creating a new file or modifying an
existing one. Python supports writing text and binary data with various methods.
Methods for Writing Text Files
a. write(string)
o Description: Writes the string to the file and returns the number of
characters written. Does not add newlines automatically.
o file.write("Hello, World!")
b. writelines(lines)
o file.writelines(lines)
Binary files are written in bytes using binary modes ("wb", "ab", "w+b").
file.write(b"Binary data")
Append Mode
In append mode ("a"), data is added to the end of the file without overwriting existing:
Error Handling
• file.write("Data")
• except PermissionError:
print("Permission denied")
Practical Applications
• Reading Files:
settings = file.readlines()
print(line.split(","))
• Writing Files:
file.write("Error occurred\n")
Classes are defined using the class keyword, followed by the class name and a colon. The
class body contains attributes and methods that define the behavior and properties of
objects created from the class.
• Classes help organize code and model real-world entities like Car, Student,
Employee, etc.
• The class itself does not occupy memory until an object is created from it.
class Car:
pass
class Car:
self.brand = brand
self.model = model
def show_details(self):
3. What is an Object?
• Objects can have their own data and can call methods defined in the class.
• Here, car1 and car2 are two different objects with their own attributes.
4. Attributes in Classes
class Student:
self.name = name
self.age = age
class Student:
self.name = name
student1 = Student("Alice")
print(student1.name) # Alice
del car1
• It is mainly used to initialize attributes (i.e., assign initial values) to the newly
created object.
• You don't call the constructor manually; Python calls it when you create an object.
• Every class has a constructor, either defined by the user or provided by Python by
default.
2. Syntax of Constructor
class ClassName:
3. Purpose of Constructor
class Student:
self.name = name
self.age = age
# Creating an object
s1 = Student("Alice", 20)
print(s1.age) # Output: 20
5. Types of Constructors
class Example:
def __init__(self):
obj = Example()
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
6. Constructor Overriding
• If you define multiple __init__() methods, only the last one is considered.
class Demo:
self.name = name
d1 = Demo()
d2 = Demo("Alex")
Inheritance in Python
1. What is Inheritance?
• It allows a new class (child class) to reuse or inherit attributes and methods from
an existing class (parent class).
• The child class can extend or modify the behavior of the parent class.
class ParentClass:
class ChildClass(ParentClass):
• The parent class name is placed inside parentheses in the child class definition.
• The child class automatically gets all public attributes and methods of the parent
class.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
pass
d = Dog()
Single Inheritance One child inherits from one parent Dog → Animal
Multiple Inheritance One child inherits from multiple parents Child → Father, Mother
Hierarchical
Multiple children inherit from one parent Dog, Cat → Animal
Inheritance
5. Single Inheritance
class Parent:
def function1(self):
class Child(Parent):
def function2(self):
c = Child()
6. Multiple Inheritance
• A child class can inherit from more than one parent class.
class Father:
def skills(self):
print("Gardening")
class Mother:
def skills(self):
print("Cooking")
pass
c = Child()
7. Method Overriding
• A child class can redefine a method of the parent class to modify its behavior.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
d = Dog()
• super() is used to call methods from the parent class inside the child class.
class Person:
self.name = name
class Student(Person):
super().__init__(name)
self.course = course
s = Student("Alice", "Maths")
print(s.name) # Alice
print(s.course) # Maths
9. Advantages of Inheritance
• Code Reusability: Methods and attributes of the parent class can be reused.
• Python does not support traditional function overloading like C++ or Java.
o Default arguments or
• Python does not allow defining two methods with the same name but different
parameters.
def greet(name):
print("Hello", name)
print(message, name)
Use default arguments to simulate overloading.
class Greet:
if name:
print("Hello", name)
else:
print("Hello there!")
g = Greet()
3. Operator Overloading
• Python lets you define special methods (also called magic methods) like __add__,
__sub__, __mul__, etc.
class Point:
self.x = x
self.y = y
def __str__(self):
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2 # Calls __add__()
• Always return a new object rather than modifying existing objects unless
necessary.
• Python already overloads operators for built-in types (like + for integers, strings,
lists).
Polymorphism in Python
1. What is Polymorphism?
o Poly = Many
o Morph = Forms
• In Python, polymorphism allows different classes to have methods with the same
name, but potentially different behaviors.
• The exact method that is called is decided at runtime based on the object's class.
2. Importance of Polymorphism
• Allows writing general-purpose code that can work with objects of different types.
3. Types of Polymorphism
Type Description
return x + y + z
PROGRAM
# -------------------- BASE CLASS WITH ENCAPSULATION --------------------
class Student:
def __init__(self, name, subject1, subject2, subject3):
self.name = name # Public attribute
self.__subject1 = subject1 # Private attributes (encapsulation)
self.__subject2 = subject2
self.__subject3 = subject3
def calculate_percentage(self):
total = self.__subject1 + self.__subject2 + self.__subject3
percentage = total / 3
return percentage
def get_subject_marks(self):
# Safely access private marks
return (self.__subject1, self.__subject2, self.__subject3)
# -------------------- INHERITANCE --------------------
class SchoolStudent(Student):
def __init__(self, name, subject1, subject2, subject3, school_name):
super().__init__(name, subject1, subject2, subject3) # Call base class constructor
self.school_name = school_name
def display_info(self):
print(f"Student Name: {self.name}")
print(f"School Name: {self.school_name}")
print(f"Marks: {self.get_subject_marks()}")
print(f"Percentage: {self.calculate_percentage():.2f}%")
# -------------------- FUNCTION OVERLOADING USING DEFAULT ARGUMENTS ------------------
class Calculator:
def add(self, a, b, c=0):
return a + b + c # Add two or three numbers depending on input
# -------------------- POLYMORPHISM --------------------
def show_student_details(student):
student.display_info()
# -------------------- MAIN PROGRAM --------------------
# Creating objects
print("\n--- Student Data Entry ---")
stu1 = SchoolStudent("Amit", 85, 90, 80, "Greenwood High")
stu2 = SchoolStudent("Riya", 78, 88, 92, "Sunrise Academy")
# Encapsulation Example
print("\n--- Encapsulation ---")
print(f"{stu1.name}'s marks are {stu1.get_subject_marks()}") # Using method to get private
data
# Inheritance and Polymorphism Example
print("\n--- Inheritance and Polymorphism ---")
show_student_details(stu1) # Student 1 details
show_student_details(stu2) # Student 2 details
# Function Overloading Example
print("\n--- Function Overloading ---")
calc = Calculator()
print(f"Sum of 10 and 20: {calc.add(10, 20)}")
print(f"Sum of 10, 20 and 30: {calc.add(10, 20, 30)}")
An unordered An ordered,
An ordered An unordered
collection of immutable
Definition collection of collection of
unique collection of
elements. key-value pairs.
elements. elements.
Immutable
Mutable (can be Mutable (can be Mutable (can be
Mutability (cannot be
changed). changed). changed).
changed).
Keys must be
Not allowed (all
unique; values
Duplicates Allowed. elements must Allowed.
can be
be unique).
duplicate.
Keys are
Supports Does not Supports
accessed
Indexing indexing and support indexing and
directly (no
slicing. indexing. slicing.
indexing).
Feature List Set Tuple Dictionary
Access
Access Access
elements by Access values
Access elements by elements by
looping (no using keys.
index. index.
direct access).
{ key: value }
[ ] (square ()
Syntax { } (curly braces) (curly braces
brackets) (parentheses)
with colon)
add(), remove(),
append(),
discard(), pop(), Few keys(), values(),
extend(),
union(), methods: items(), get(),
Methods/Functions insert(), pop(),
intersection(), count(), update(), pop(),
remove(), sort(),
difference(), index() etc.
reverse(), etc.
etc.
More memory
Least
(due to Less memory More memory
memory
Memory Consumption mutability and (no duplicates, (stores mapping
(immutable
dynamic unordered). of key to value).
and simple).
features).
Storing an Fixed
Associating
ordered Storing a collection of
keys with values
Best For collection when collection of items that
(mapping
duplicates are unique items. should not
relationships).
allowed. change.