M6
M6
Key Concepts
3. Using Step Value
1. Indexing – Accessing Individual Characters
You can skip characters using a step value.
Each character in a string has an index number:
s = "Python"
P y t h o n
print(s[::2]) # Pto (every 2nd character)
0 1 2 3 4 5
print(s[::-1]) # nohtyP (reversed)
Example:
word = "Python"
4. Splitting and Joining
print(word[0]) # P
You can break a string into parts or combine parts back together.
print(word[5]) # n
sentence = "Machine Learning with Python"
print(word[-1]) # n
parts = sentence.split() # ['Machine', 'Learning', 'with', 'Python']
print(word[-3]) # h
print(parts[1]) # Learning
If you want both the index and the character, you can use range() h
or enumerate(). t
Using range(): y
word = "Data" P
for i in range(len(word)):
print(i, word[i]) Example 4: Counting Occurrences
Output: Traversal helps perform tasks like counting characters.
0D word = "banana"
1a count = 0
2t for char in word:
3a if char == 'a':
Using enumerate(): count += 1
for index, char in enumerate("Science"): print("Number of a's:", count)
print(index, char) Output:
Number of a's: 3
Example 3: Traversing Backwards
You can also traverse the string in reverse order.
s = "Python"
for i in range(len(s)-1, -1, -1):
print(s[i])
Q6. Why is Traversal important in Python? Part Meaning
Answer: step (Optional) Number of characters to skip
Traversal is important because it helps in:
1. Analyzing strings – counting, searching, or validating
characters. Example 1 – Basic Slicing
Q8. What is the syntax of slicing in Python? print(text[:4]) # From beginning → 'Data'
end Index where the slice stops (exclusive) print(name[0:8:2]) # Every 2nd character
Output: Q9. Why is slicing useful in Python?
Jnta Answer:
Slicing is useful because it allows you to:
1. Extract specific parts of a string easily.
Negative indices count from the end of the string. 3. Skip characters using the step parameter.
If you want to “change” part of a string, you actually create a new o Python stores strings in a way that allows them to be
string using concatenation or slicing. shared safely between variables.
Q Explain the concept of Tuples as Return Values in Python with • The returned tuple can then be stored in a single variable or
examples. unpacked into multiple variables.
Answer:
In Python, a function can return multiple values at once by 4. Unpacking the Returned Tuple
grouping them into a tuple. You can assign the returned tuple values to separate variables
This allows returning several related results together from a single using tuple unpacking.
function call.
sum_, diff = add_sub(10, 5)
print(sum_) # 15
1. Definition
print(diff) # 5
Tuples as return values mean returning multiple results from a
function using a single tuple.
Python automatically packs the returned values into a tuple when a 5.Using tuples for returning values makes functions more flexible
function returns more than one value. and organized, especially when multiple outputs are logically
related (such as coordinates, statistics, or results of calculations).
2. Example
def add_sub(x, y):
return x + y, x - y
1. Simple Definition
4. Real-Life Use
Composability of data structures means combining multiple data
structures to build more powerful and flexible data models. It is commonly used for storing structured data such as:
It refers to the ability to nest or mix data structures such as using a • Student records (name, marks, subjects)
list inside a tuple, a tuple inside a list, or a list inside a dictionary. • Employee information (ID, name, salary)
• Course or project details
2. Example
A tuple can hold a list as one of its elements:
student = ("ALEX", [85, 90, 95]) 5. Composability allows developers to combine data structures like
lists, tuples, and dictionaries to create organized, flexible, and
print(student) efficient representations of complex real-world data.
Output:
('ALEX', [85, 90, 95])
The in and not in Operators in Strings (5 Points) Q.Explain the use of in and not in operators in strings with
1. Definition: examples.
The in and not in operators are used to check whether a Answer:
substring exists inside a string. The in and not in operators in Python are used to check the
2. in Operator: presence or absence of a substring within another string. They
Returns True if the substring is found in the main string. return Boolean values (True or False) based on the result.
4. Purpose:
These operators are used for searching or filtering text data 2. The in Operator
easily. The in operator returns True if the specified substring is found in
5. Example: the main string.
text = "Python is fun" Example:
5. Example
2. Example
numbers = [10, 20, 30]
a = [1, 2, 3]
for n in numbers:
b=a
print(n * 2)
Here, both a and b refer to the same list object in memory.
Output:
20
3. Effect
40
If one variable modifies the object, the other variable also reflects
60 the change.
b[0] = 10
Conclusion: print(a) # Output: [10, 2, 3]
The combination of lists and for loops provides a simple and
powerful way to handle multiple elements efficiently in Python
programs.
4. In Python, lists and other mutable objects are stored by Explain the concept of Cloning Lists in Python with examples.
reference, not by value. Answer:
Cloning a list means creating a new copy of an existing list so that
5. This means both variables point to the same memory address changes made to one list do not affect the other.
rather than creating separate copies. This is useful for avoiding unintended modifications due to aliasing.
2. Example
a = [1, 2, 3]
b = a[:] # Cloning using slicing
print(b) # Output: [1, 2, 3]
Here, a and b look identical but are stored separately in memory.
3. Purpose
Cloning helps to avoid aliasing, ensuring each list works
independently.
Any change in one list will not affect the cloned list.
2. Example
a = [1, 2, 3]
b = a[:] # Cloning using slicing
print(b) # Output: [1, 2, 3]
Here, a and b look identical but are stored separately in memory.
3. Purpose
Cloning helps to avoid aliasing, ensuring each list works
independently.
Any change in one list will not affect the cloned list.
1. Definition
• Looping: The process of accessing each character in a string
one by one.
• Counting: The process of finding how many times a particular
character or substring occurs within a string.
5. Importance
3. Syntax Optional parameters are useful for:
An optional parameter is declared by assigning a default value in • Reducing code repetition
the function definition.
• Providing default behavior for functions
def display_info(student, course="Data Science"):
• Handling missing or incomplete inputs gracefully
print("Student:", student)
print("Course:", course)
Q Explain user-defined and built-in find() methods in Python with • The substring "Science" begins at index 5.
examples. • Since "Python" is not present, the method returns -1.
Answer:
The find() method is used to locate the position of a substring
within a given string. 3. User-defined find() Method
Python provides a built-in find() method, and users can also define You can create your own function to find a substring manually
their own version to achieve similar functionality using loops. using a loop.
Example:
1. Definition def find(text, sub):
• The built-in find() method searches for a substring in a string for i in range(len(text) - len(sub) + 1):
and returns the index of its first occurrence.
if text[i:i+len(sub)] == sub:
• If the substring is not found, it returns -1.
return i
• A user-defined find() function performs the same operation
return -1
manually using iteration.
sentence = "apple,banana,cherry"
print(sentence.split(",")) # Output: ['apple', 'banana', 'cherry']
Use:
Used to break strings into words or items, often in data cleaning or
text processing.
2. strip() Method
Definition: # Output: Student: ALEX, Course: Data Science
The strip() method removes unwanted spaces or characters from Use:
the beginning and end of a string. Used for string formatting to make output more readable and
Syntax: structured.
string.strip(characters)
Example:
text = " Data Science " 4. Importance
print(text.strip()) # Output: 'Data Science' These string methods are widely used in:
• Text processing and cleaning
word = "@hello@" • Data formatting and reporting
print(word.strip("@")) # Output: 'hello' • Preparing user-friendly program outputs
Use:
Used for cleaning input data or removing special symbols before
processing.
3. format() Method
Definition:
The format() method is used to insert values into a string
dynamically using placeholders {}.
Syntax:
string.format(value1, value2, ...)
Example:
name = "ALEX"
course = "Data Science"
print("Student: {}, Course: {}".format(name, course))
Q.Explain cleaning and formatting of strings in Python with sentence = "Python is fun"
examples. words = sentence.split()
Answer: cleaned = " ".join(words)
In Python, cleaning and formatting strings are common text
processing tasks. print(cleaned) # Output: Python is fun
Cleaning refers to removing unwanted spaces, symbols, or
characters, while formatting refers to organizing or presenting text
3. String Formatting Methods
neatly for output or display.
After cleaning, strings can be formatted for clear output.
(a) Using format()
1. Definition
name = "Amith"
• Cleaning strings: Removing unnecessary characters such as
spaces, punctuation, or symbols from a string. course = "Data Science"
• Formatting strings: Structuring the cleaned string in a print("Student: {}, Course: {}".format(name, course))
readable and meaningful format using built-in methods like # Output: Student: Amith, Course: Data Science
format() or f-strings.
(b) Using f-strings (Python 3.6+)
marks = 95
2. String Cleaning Methods
print(f"Amith scored {marks}% in Python.")
Python provides several methods to clean strings easily.
# Output: Amith scored 95% in Python.
(a) Using strip() – Removes extra spaces from both ends.
text = " Data Science "
4. Purpose
cleaned = text.strip()
Cleaning and formatting strings are used to:
print(cleaned) # Output: Data Science
• Prepare data for analysis or machine learning
(b) Using replace() – Removes or replaces unwanted characters.
• Improve readability and presentation of output
s = "Python@3.12"
• Remove extra symbols or spaces from user input or datasets
print(s.replace("@", " ")) # Output: Python 3.12
(c) Using split() and join() – Removes extra spaces within text.
5. Example Explain pure functions in Python with examples.
text = " Hello@World! " Answer:
cleaned = text.strip().replace("@", " ").replace("!", "") A pure function in Python is a function that does not modify the
original data.
formatted = f"Cleaned Text: {cleaned}" It takes input values, performs computations, and returns a new
print(formatted) result without causing any side effects.
Output:
Cleaned Text: Hello World 1. Definition
A pure function is one that does not change the original data; it
only uses the given inputs to produce a new result.
2. Working
A pure function takes arguments, performs operations, and returns
a new value while keeping the original data unchanged.
Example:
nums = [1, 2, 3]
new_nums = sorted(nums)
print(nums) # Output: [1, 2, 3]
print(new_nums) # Output: [1, 2, 3]
Here, sorted() creates a new list and does not modify the original
list nums.
3. Data Unchanged
After calling a pure function, the original data remains the same.
This makes programs more reliable and easier to debug.
Q. Explain modifier functions in Python with examples.
4. Characteristics Answer:
• Pure functions are safe and predictable — the same input A modifier function is a type of function that changes or updates
always produces the same output. the original data directly instead of returning a new, modified
copy.
• They do not depend on or modify external variables. These functions work in place and alter the content of the existing
• They avoid side effects, making them easier to test and reuse. data structure.
2. Working
Modifier functions perform operations in place on mutable data
6.Pure functions improve code reliability and clarity by keeping types (like lists), changing their content permanently.
data unmodified and ensuring consistent output for the same
inputs.
3. Example
7.They are an essential part of clean and functional programming nums = [1, 2, 3]
practices. nums.sort()
print(nums) # Output: [1, 2, 3]
Here, the sort() function changes the order of elements within the
same list — no new list is created.
4. Key Feature
The original object is updated, and no new copy is created.
This means both the variable and the data it refers to are changed.
5. Characteristics and Usefulness Explain accessing elements and list membership in Python with
• Modifier functions are in-place operations that directly affect examples.
existing data. Answer:
• They are useful when you want to save memory or avoid
duplication by updating the data itself instead of creating a
new version. 1. Accessing Elements (Definition)
Each element in a list has an index number, starting from 0 for the
6. Common Modifier Functions first element.
Some commonly used modifier functions in Python include: You can use the index to access or modify elements individually.
• list.append() – adds an element to the end of the list fruits = ["apple", "banana", "cherry"]
2. Negative Indexing
7.Modifier functions directly alter existing data without creating Python allows negative indexing, where -1 refers to the last
new copies. element, -2 to the second-last, and so on.
Example:
8.They are efficient for memory management but should be used fruits = ["apple", "banana", "cherry"]
carefully to avoid unintended data changes.
print(fruits[-1]) # Output: cherry
print(fruits[-2]) # Output: banana
5. Importance
3. List Membership (Definition) Accessing and membership operations are essential for:
Membership operators in and not in are used to check whether an • Retrieving and validating data from lists
element exists in a list. • Searching, modifying, and filtering items
They return True or False based on the result.
• Writing loop-based programs and conditional logic efficiently
Example:
numbers = [10, 20, 30, 40]
print(20 in numbers) # Output: True 6.Accessing elements and checking list membership are
print(50 not in numbers) # Output: True fundamental list operations in Python.
4. Combined Example 7.They make it easy to work with, analyze, and manipulate list data
effectively.
You can use both indexing and membership checks together to
process list data efficiently.
Example:
students = ["Amith", "Rahul", "Priya"]
if "Priya" in students:
print("Priya found at index:", students.index("Priya"))
Output:
Priya found at index: 2
Explain Nested Lists in Python with examples. apple banana cat dog 1 2 3
Answer:
A nested list is a list that contains one or more lists inside it. 4. Use and Purpose
It helps organize related groups of data and represent hierarchical
or multi-level structures. Nested lists are useful for storing:
• Grouped or hierarchical data
A nested list is a list within another list, where each inner list acts • Lists of student marks, product details, etc.
as an element of the outer list.
It can store mixed data types and multiple layers of information.
5.Nested lists allow multi-level data storage within a single
Example: variable, making complex data easier to organize and process.
nested = [["apple", "banana"], ["cat", "dog"], [1, 2, 3]]
2. Accessing Elements 6.Nested lists provide a flexible way to store and access structured
or layered data efficiently in Python.
To access elements inside a nested list, you use multiple indices —
one for the outer list and one for the inner list.
print(nested[0][1]) # Output: banana
print(nested[2][2]) # Output: 3
print(matrix[0][2]) # Output: 3
print(matrix[2][1]) # Output: 8 5. Purpose and Importance
Matrices are used for:
You can use nested loops to visit every element of a matrix. • Image and data representation