0% found this document useful (0 votes)
5 views46 pages

Module 2

Module 2 covers string manipulation in Python, including string methods, indexing, and comparison. It explains the immutability of strings, various built-in functions like split() and join(), and introduces tuples and lists. The module emphasizes the use of for loops for string traversal and provides examples of string operations and testing methods.

Uploaded by

Ayush Das
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views46 pages

Module 2

Module 2 covers string manipulation in Python, including string methods, indexing, and comparison. It explains the immutability of strings, various built-in functions like split() and join(), and introduces tuples and lists. The module emphasizes the use of for loops for string traversal and provides examples of string operations and testing methods.

Uploaded by

Ayush Das
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 2

Working with strings as single things, working with the parts of a string, Length, Traversal and the for
loop, Slices, String comparison. Strings are immutable, the in and not in operators. A find function,
optional parameters. The built-in find method. The split method, Cleaning up your strings. The string
format [Link]: Tuples are used for grouping data, Tuple assignment, Tuples as return values,
Composability of Data Structures. Lists: List values, accessing elements, List length, List membership,
List operations, List slices, Lists are mutable, List deletion, Objects and references, Aliasing, cloning
lists, Lists and for loops, List parameters, List methods, Pure functions and modifiers, Functions that
produce lists, Strings and lists, list and range, Nested lists, Matrices.

String

A string is a sequence of characters enclosed in quotes.

Example

s = "Hello"

Working with Strings as Single Things

Just like a turtle in the turtle module is an object with: attributes (color, position, etc.),methods
(forward(), left(), etc.)​
A string is also an object in Python.

●​ Every string has its own methods​

●​ We can call those methods using dot notation

Example
our_string = "Hello, World!"
all_caps = our_string.upper()

What happens here?

●​ our_string is a string object.​

●​ .upper() is a method applied to that string.​

●​ It returns a new string in uppercase.​

●​ The original string remains unchanged.​

Output:

Python Programming (BBPYPB205), Department of CSE Module 2


1
'HELLO, WORLD!'

string methods

Case Conversion Methods

✔ upper()

Converts all letters to uppercase.

"python".upper()

Output: "PYTHON"

✔ lower()

Converts all letters to lowercase.

"HELLO".lower()

✔capitalize()

Capitalizes only the first letter.

"python".capitalize()

✔ swapcase()

Changes uppercase to lowercase and vice versa.

"PyThOn".swapcase()

Searching & Checking Methods

✔ find()

Returns index of first occurrence.

"banana".find("na")

✔ count()

Counts how many times a substring appears.

"banana".count("a")

Python Programming (BBPYPB205), Department of CSE Module 2


2
✔ startswith()

Checks if string starts with given value.

"Python".startswith("Py")

✔ endswith()

Checks if string ends with given value.

"Python".endswith("on")

Replace & Modify

✔ replace()

Replaces part of string.

"Hello world".replace("world", "Python")

✔ strip()

Removes extra spaces from both sides.

" hello ".strip()

split() Method

Purpose:

Converts a string into a list by splitting it at a specified separator.

🔹 Syntax:
[Link](separator)

🔹 Example:
"a,b,c".split(",")

🔹 Output:
['a', 'b', 'c']

Explanation:

●​ The comma , is the separator.​

Python Programming (BBPYPB205), Department of CSE Module 2


3
●​ The string is broken wherever a comma appears.​

●​ The result is a list of substrings.

If no separator is given, it splits by space by default.

Example:

"Hello World Python".split()

join() Method (Python)

Combines elements of a list (or iterable) into a single string using a specified separator.​

Syntax:

[Link](iterable)

Example:

",".join(["a", "b", "c"])

Output:

'a,b,c'

Explanation:

In this case, the comma , acts as the separator used to join the elements of a list. When the join() method
is applied, it takes each element from the list and combines them into a single string, placing the
separator between each element. This means that instead of having separate items in a list, all elements
are merged together with the specified separator in between, resulting in one complete string.

Example:

" ".join(["Hello", "World", "Python"])

Output:

'Hello World Python'

●​ All elements in the iterable must be strings, otherwise an error will occur.

String Testing Methods in Python

Python Programming (BBPYPB205), Department of CSE Module 2


4
String testing methods are used to check whether a string satisfies a certain condition. These methods
return True or False.

Common String Testing Methods

1. isalnum()

●​ Checks if the string contains only letters and numbers.​

"abc123".isalnum()

Output: True

2. isalpha()

●​ Checks if the string contains only alphabetic characters.​

"Python".isalpha()

Output: True

3. isdigit()

●​ Checks if the string contains only digits.​

"12345".isdigit()

Output: True

Indexing in Strings

A string is a sequence of characters stored in order.​


Python allows us to access individual characters using indexing.

Indexing uses square brackets [ ].

Python Programming (BBPYPB205), Department of CSE Module 2


5
1. Positive Indexing (Left to Right)

●​ Starts at 0. In programming, we almost always start counting at zero.


●​ Use case: Best when you know the exact position from the beginning of the string.
●​ Example: string[0] gives you "H", and string[6] gives you "P".

2. Negative Indexing (Right to Left)

●​ Starts at -1. The very last character is always -1.


●​ Use case: This is incredibly useful when you want to grab the end of a string without knowing its
total length.
●​ Example: string[-1] gives you the last letter "N", and string[-12] brings you back to the start
"H".

A = "HELLO PYTHON"

print(A[2]) // Output: L
print(A[-5]) // Y
Print(A[0]) // H
print(A[11]) // N
print(A[5]) // space

Python Programming (BBPYPB205), Department of CSE Module 2


6
enumerate()

It is a built-in function that adds a counter (index) to an iterable (like string, list, tuple).It allows you to
access:

●​ Index (position)
●​ Value (element)​
at the same time.

Syntax

enumerate(iterable, start=0)

Parameters: iterable → string, list, tuple, etc, start → optional starting index (default = 0)

Example:

text = "Python"

for index, value in enumerate(text):

print(index, value)

Using start Parameter

fruits = ["Apple", "Mango", "Banana"]

for i, fruit in enumerate(fruits, start=1):

print(i, fruit)

Output:

1 Apple

2 Mango

3 Banana

Python Programming (BBPYPB205), Department of CSE Module 2


7
Length
The built-in len() function returns the total number of characters in a string.

Example:

word = "banana"

len(word) // Output:6

Why Does This Cause an Error?

size = len(word)

last = word[5] # ERROR! IndexError: string index out of range

Traversal and the for Loop

Traversal means processing each character of a string one by one, usually from the beginning to the
end. Many programs need to Check each character,Count letters,Modify text,Print characters
separatelyThis step-by-step processing is called string traversal.

The for loop is considered better in Python because it is shorter, clearer, and easier to understand
compared to other looping methods like the while loop. It reduces the amount of code needed and avoids
manually handling index values, which makes the program more readable. Since there is no need to
explicitly update variables (like incrementing an index), it is less error-prone and helps prevent common
mistakes such as infinite loops. Overall, the for loop follows Python’s simple and clean coding style,
making it more “Pythonic” and preferred for iteration.

In a for loop, Python automatically selects each character from the string one by one during iteration, so
there is no need to manually use an index to access elements. This means you do not have to rely on
functions like len() to control the loop. The loop continues smoothly through all characters and stops
automatically once it reaches the end of the string. This makes the process simple, efficient, and easy to
use.

word = "Banana"
for letter in word:
print(letter)
Output:
B
a
n
a

Python Programming (BBPYPB205), Department of CSE Module 2


8
n
a

Using Traversal with Concatenation


prefixes = "JKLMNOPQ"

suffix = "ack"

for p in prefixes:

print(p + suffix)

Output

Jack

Kack

Lack

Mack

Nack

Oack

Pack

Qack

Slices

string slicing means extracting a part (substring) of a string using index positions.

Syntax
string_name[start : end]

●​ start → Starting index (included)​

●​ end → Ending index (excluded)​

●​ Indexing starts from 0

Python Programming (BBPYPB205), Department of CSE Module 2


9
text = "Python”

print(text[0:4])

Output: Pyth

P y t h o n

0 1 2 3 4 5

print(text[:3]) // Pyt

print(text[2:]) // thon

print(text[:]) // Python

String Comparison in Python

In Python, strings can be compared using comparison operators like:

●​ == → equal
●​ != → not equal
●​ < → less than
●​ > → greater than
●​ <= → less than or equal
●​ >= → greater than or equal

These comparisons are based on lexicographical (dictionary) order using ASCII/Unicode values.

1. Checking Equality (==)

Example:
word = "banana"

if word == "banana":

print("Yes, we have no bananas!")

Output:
Yes, we have no bananas!

Python Programming (BBPYPB205), Department of CSE Module 2


10
The == operator is used to check whether two strings are exactly the same. It compares each character of
both strings one by one and also ensures that the order of characters is identical. If every character
matches in the same sequence, the condition becomes true. In this example, since the string "banana" is
compared with "banana" and both have the same characters in the same order, the condition evaluates to
True.

2. Lexicographical Comparison (<, >)

Example:
if word < "banana":

print("Your word comes before banana.")

elif word > "banana":

print("Your word comes after banana.")

else:

print("Same word!")

Python compares strings in a character-by-character manner when using comparison operators. It starts
by comparing the first character of both strings; if they are equal, it moves on to the next character. This
process continues step by step, checking each corresponding character in sequence, until a difference is
found. As soon as a mismatch occurs, Python determines the result of the comparison based on the
ASCII/Unicode values of the differing characters.

3. Internal Working

Example:
"apple" < "banana"

True

The expression evaluates to True because Python compares the strings starting with their first
characters. In this case, it compares 'a' from the first string with 'b' from the second string. Since the
ASCII value of 'a' is less than the ASCII value of 'b', Python determines that the first string is smaller,
and therefore the comparison returns True.

4. ASCII Rule (Important)

Python Programming (BBPYPB205), Department of CSE Module 2


11
●​ Uppercase letters (A–Z) have smaller ASCII values
●​ Lowercase letters (a–z) have larger ASCII values

Example:
"Zebra" < "banana"

True

When comparing the strings, Python first looks at the first characters, which are 'Z' and 'b'. It then
checks their ASCII values, where the value of 'Z' is smaller than that of 'b'. Because of this, Python
determines that 'Z' comes before 'b', and therefore the comparison evaluates to True.

5. Fixing the Problem (Using lower())

Example:
word = "Zebra"

if [Link]() < "banana":

print("Before banana")

False

The lower() function converts all characters in a string to lowercase, which helps ensure a fair
comparison. In this case, "Zebra" becomes "zebra", and the comparison is now "zebra" < "banana".
Python compares the first characters, 'z' and 'b', and since the ASCII value of 'z' is greater than 'b', it
determines that "zebra" comes after "banana". Therefore, the result of the comparison is False.

Strings Are Immutable

In Python, once a string is created, it cannot be changed, which means strings are immutable. In the
given example,

greeting = "Hello, world!", when we try to change the first character using

greeting[0] = 'J'

Python raises an error. This is because indexing in strings is only used to access characters, not to
modify them. Since strings do not support changing individual characters directly, Python throws a
TypeError stating that a string object does not support item assignment. To modify a string, we must
create a new string instead of changing the existing one.

Python Programming (BBPYPB205), Department of CSE Module 2


12
Instead of modifying, we create a new string:

greeting = "Hello, world!"


new_greeting = "J" + greeting[1:]
print(new_greeting)
What is happening?

●​ greeting[1:] → takes everything except first character​

●​ "J" + greeting[1:] → adds new first letter​

●​ Creates a completely new string

Output:

Jello, world!

Original string remains unchanged.

The in and not in Operators in Python

The in Operator (Membership Operator)

The in operator is used to check whether something exists inside something else.

When both operands are strings, in checks whether the left string is a substring of the right string.

Syntax:
substring in main_string

If the substring is found → returns True​


If not found → returns False

"p" in "apple" → True

"i" in "apple" → False

"ap" in "apple" → True

"pa" in "apple" → False

1.​ A string is always a substring of itself:

Python Programming (BBPYPB205), Department of CSE Module 2


13
"apple" in "apple" → True
"a" in "a" → True

2.​ The empty string "" is considered a substring of every string:

"" in "a" → True


"" in "apple" → True

Because an empty string technically exists at every position inside a string.

The not in Operator

The not in operator is just the opposite of in.

Syntax:
substring not in main_string

If substring is NOT found → returns True​


If substring is found → returns False

Example:

"x" not in "apple" → True


"p" not in "apple" → False

Example: Removing Vowels Using not in

def remove_vowels(phrase):

vowels = "aeiou"

string_sans_vowels = “”

for letter in phrase:

if [Link]() not in vowels:

string_sans_vowels += letter

return string_sans_vowels

find() function

The find() function in Python is used to search for a substring within a string. It returns the index
Python Programming (BBPYPB205), Department of CSE Module 2
14
(position) of the first occurrence of the specified substring. If the substring is not found, it does not raise
an error; instead, it returns -1, making it a safe way to perform searches. The syntax of the function is
[Link](substring, start, end), where substring is the value you want to search for, start is an optional
parameter that specifies the index from where the search should begin, and end is another optional
parameter that defines the position where the search should stop.

Basic Example
text = "Bananarama!"
print([Link]("a"))

Output:
1

Because the first "a" appears at index 1.

If Substring Not Found


text = "apple"
print([Link]("z"))

Output:
-1
So unlike some functions, it does not give an error, it safely returns -1.

Searching for a Word (Not Just a Character)


text = "I like apples"
print([Link]("like"))

Output:
2

Because "like" starts at index 2.

Using Start Position


text = "banana"
print([Link]("a", 2))

Output:
3
Python Programming (BBPYPB205), Department of CSE Module 2
15
It starts searching from index 2

Looping and counting


Looping and counting is a common concept in Python used to process each element of a string or list
and keep track of how many times a particular condition is met. In this approach, a loop (usually a for
loop) is used to traverse through each character or element one by one. At the same time, a counter
variable is maintained, which is initialized to zero and increased whenever a specific condition is
satisfied, such as finding a particular letter or number. This method is useful for tasks like counting
occurrences, searching patterns, or analyzing data. Overall, looping helps in iteration, while counting
helps in keeping track of results during that iteration.

def count_a(text):

count = 0

for letter in text:

if letter == "a":

count += 1

return(count)

print(count_a("banana") == 3)

Output: True

optional parameter

An optional parameter is a function parameter that has a default value assigned in the function
definition.

If the user does not provide a value for that parameter while calling the function, Python automatically
uses the default value.

Basic Syntax

def function_name(parameter = default_value):


# function body

Simple Example
def greet(name="Student"):

Python Programming (BBPYPB205), Department of CSE Module 2


16
print("Hello", name)

Function Calls:
greet("Yashaswini")

Output:

Hello Yashaswini
greet()

Output:

Hello Student

Since no argument was given, "Student" (default value) is used.

split() method

The split() method in Python is used to divide a string into a list of smaller parts based on a specified
separator. It breaks the string wherever the separator occurs and returns a list containing the resulting
substrings. If no separator is provided, Python automatically splits the string based on spaces. This
method is very useful when working with sentences, data processing, or user input where values need to
be separated and handled individually.

Example

text = "Hello World Python"

words = [Link]()

print(words)

Output: ['Hello', 'World', 'Python']

cleaning up your string

Cleaning a string means removing unwanted characters such as punctuation marks (like ! , . ? ; :),
newline characters (\n), tabs (\t), and extra spaces to make the text neat and easier to process. This is
especially important when performing tasks like counting word frequency, checking spelling, analyzing
text from files or the internet, or handling user input, where unwanted symbols can affect accuracy. One
common way to clean a string is by using a loop to examine each character and remove unwanted ones.
For example, using [Link], we can check whether a character is a punctuation mark and skip
it while building a new cleaned string.
Python Programming (BBPYPB205), Department of CSE Module 2
17
The function remove_punctuation() works by iterating through each letter in the given phrase and
adding only those characters that are not punctuation to a new string. In addition to this approach,
built-in methods like .split() can also help in cleaning and organizing text by breaking it into meaningful
parts.

import string
def remove_punctuation(phrase):
cleaned = ""
for letter in phrase:
if letter not in [Link]:
cleaned += letter
return cleaned
The String Format Method

String formatting is the process of inserting values (variables) into a string in a clean and readable way.

Instead of joining strings using +, formatting lets us embed variables inside strings easily.

Example:
name = "Yashaswini"
age = 20

print("My name is {} and I am {} years old.".format(name, age))

Output:

My name is Yashaswini and I am 20 years old.

Using Index Numbers


print("My name is {0} and I am {1} years old.".format(name, age))

Using Named Arguments


print("My name is {n} and I am {a} years old.".format(n=name, a=age))

f-Strings (Recommended – Modern Way)​


This is the easiest and most powerful method.

Example:

Python Programming (BBPYPB205), Department of CSE Module 2


18
name = "Yashaswini"
age = 20

print(f"My name is {name} and I am {age} years old.")

Output:

My name is Yashaswini and I am 20 years old.

Tuples

Tuples are used for grouping data

Tuples are used for grouping data by storing multiple related values together in a single variable. A tuple
is a collection of elements written using parentheses (), and it can contain different data types such as
strings, integers, or more. Tuples are ordered, which means the elements maintain their position, and
they are immutable, meaning their values cannot be changed after creation. This makes tuples useful
when we want to store fixed data that should not be modified

Example:

student = ("Sai", 21, "CSE")


print(student)
Output: ('Sai', 21, 'CSE')

Tuple Assignment

Tuple assignment is a feature in Python that allows you to assign multiple values to multiple variables in
a single line. It works by unpacking the values from a tuple (or any iterable) and assigning them to
corresponding variables in order. This makes the code shorter, cleaner, and easier to read compared to
assigning each variable separately.

Example:

name, age, course = ("Sai", 21, "CSE")

print(name) # Sai

print(age) # 21

print(course) # CSE

Python Programming (BBPYPB205), Department of CSE Module 2


19
Tuple assignment is also very useful for swapping values between variables without using a temporary
variable. For example:

a = 10

b = 20

a, b = b, a

print(a, b) # 20 10

Here, Python automatically swaps the values of a and b using tuple assignment.

Overall, tuple assignment simplifies code, reduces the number of lines, and is considered a more
Pythonic way of handling multiple assignments.

Tuples as Return Values

In Python, functions can return multiple values at once by using tuples. When we return more than one
value separated by commas, Python automatically groups them into a tuple. This makes it easy to send
back multiple results from a function without needing separate variables or complex data structures.

Example:

def calculate(a, b):

sum = a + b

diff = a - b

return sum, diff

result = calculate(10, 5)

print(result)

Output: (15, 5)

Composability of Data Structures

Composability of data structures means that different data structures in Python, such as lists, tuples, and
dictionaries, can be combined or nested inside one another to represent more complex data. Instead of
using a single data structure, we can build structured and organized data by placing one type inside

Python Programming (BBPYPB205), Department of CSE Module 2


20
another. This makes programs more flexible and powerful when handling real-world data.

For example, a tuple inside a list can be used to store multiple records, such as student names and
marks. A list inside a tuple can group related collections together while keeping the overall structure
fixed. Similarly, a dictionary inside a tuple can store key-value pairs within a grouped structure. This
ability to combine data structures allows us to organize information in a hierarchical way, making it
easier to access, manage, and process data efficiently in Python programs.

Example : List of Tuples


students = [("Sai", 80), ("Ravi", 90), ("Anu", 85)]

for name, marks in students:


print(name, marks)

Output:

Sai 80
Ravi 90
Anu 85

Tuple Containing Lists

data = ([1, 2, 3], [4, 5, 6])


print(data)

Output:

([1, 2, 3], [4, 5, 6])

Lists

List Values

Python Programming (BBPYPB205), Department of CSE Module 2


21
A list value in Python refers to a collection of items stored together in a single variable. These items can
be of the same type (like all numbers) or different types (such as a mix of numbers, strings, and boolean
values). Lists are ordered, meaning each element has a fixed position, and they are written using square
brackets [ ] with elements separated by commas. List values are very useful when we need to store
multiple related pieces of data in one place.

Syntax:
list_name = [value1, value2, value3, ...]

Example 1 (Same Data Type):


numbers = [10, 20, 30, 40]
print(numbers)

Output:
[10, 20, 30, 40]

Example 2 (Different Data Types):


data = [10, "Python", 3.5, True]
print(data)

Output:
[10, 'Python', 3.5, True]

Accessing Elements

Accessing elements in a list means retrieving individual items from the list using their position, known
as an index. In Python, lists are ordered, so each element is assigned an index starting from 0. This
means the first element is at index 0, the second at index 1, and so on. We can also use negative
indexing to access elements from the end of the list, where -1 refers to the last element, -2 to the second
last, and so forth. This makes it easy to access any element in the list directly.

Syntax:
list_name[index]

Example:
fruits = ["Apple", "Banana", "Mango", "Orange"]

print(fruits[0]) # Apple (first element)

Python Programming (BBPYPB205), Department of CSE Module 2


22
print(fruits[2]) # Mango
print(fruits[-1]) # Orange (last element)
print(fruits[-2]) # Mango

In this example, elements are accessed using both positive and negative indexing, allowing flexible
retrieval of values from the list.

List Length

The length of a list refers to the total number of elements present in the list. In Python, we use the
built-in function len() to find the length of a list. This function counts all the items in the list and returns
the number as an integer. Knowing the length of a list is useful when performing operations like looping,
indexing, or checking whether a list is empty or not.

Syntax:

len(list_name)

Example:

numbers = [5, 10, 15, 20, 25]

print(len(numbers))

Output:

List Membership

List membership in Python refers to checking whether a particular element exists in a list or not. This is
done using membership operators, namely in and not in. The in operator returns True if the specified
element is present in the list, and False otherwise. On the other hand, the not in operator returns True if
the element is not present in the list. This concept is very useful when searching for values, validating
input, or making decisions based on whether an item exists in a list.

Syntax:

element in list_name

element not in list_name

Python Programming (BBPYPB205), Department of CSE Module 2


23
Example:

numbers = [10, 20, 30, 40]

print(20 in numbers) # True

print(50 in numbers) # False

print(50 not in numbers) # True

In this example, Python checks whether the given element is present in the list and returns a Boolean
value (True or False) accordingly.

List Operations

List operations in Python are the various actions that can be performed on lists to manipulate or work
with their elements. These operations include combining lists, repeating lists, and checking for
membership. They help in organizing and processing data efficiently. Lists are flexible, so we can easily
perform different operations using simple operators.

Types of List Operations

1. Concatenation (Combining Lists)

We can combine two or more lists using the + operator.

Syntax:

list1 + list2

Example:

a = [1, 2, 3]

b = [4, 5]

print(a + b)

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

2. Repetition

We can repeat the elements of a list using the * operator.


Python Programming (BBPYPB205), Department of CSE Module 2
24
Syntax:

list_name * number

Example:

nums = [1, 2]

print(nums * 3)

Output:

[1, 2, 1, 2, 1, 2]

3. Membership Operation

Check whether an element exists in the list using in and not in.

Syntax:

element in list_name

element not in list_name

Example:

nums = [10, 20, 30]

print(20 in nums) # True

print(50 not in nums) # True

List Slices :
List slicing in Python is a technique used to extract a part (sub-list) from an existing list by specifying a
range of indices. Instead of accessing one element at a time, slicing allows you to retrieve multiple
elements in a single operation.

Syntax:

List[start:end:step]

Example:

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

Python Programming (BBPYPB205), Department of CSE Module 2


25
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[::2]) # [10, 30, 50]

Lists are Mutable:


In Python, lists are considered mutable, which means their elements can be changed, updated, added, or
removed even after the list has been created. Unlike immutable data types such as strings or tuples, a list
does not require creating a new object when modifications are made; instead, the changes are applied
directly to the existing list in memory. This allows programmers to efficiently update data without extra
memory usage. For example, you can modify a specific element using its index, append new items, or
delete existing ones. Because of this property, lists are very flexible and widely used when working with
collections of data that need to change during program execution.
numbers = [10, 20, 30]
numbers[1] = 50
print(numbers)

Output

[10, 50, 30]

List Deletion :
List deletion in Python refers to removing elements from a list using different methods depending on the
requirement. The most common ways are del, remove(), and pop().

The del statement is used to delete an element by its index or even remove the entire list.
Example:
numbers = [1, 2, 3, 4]
del numbers[2]
print(numbers) # [1, 2, 4]

The remove() method deletes the first occurrence of a specified value from the list, making it useful
when you know the element but not its position.
Example:
numbers = [1, 2, 3, 2]
[Link](2)
print(numbers) # [1, 3, 2]

The pop() method removes an element based on its index (default is the last element) and also returns
the removed value, which can be useful for further processing.

Python Programming (BBPYPB205), Department of CSE Module 2


26
Example:
numbers = [1, 2, 3]
[Link](1)
print(numbers) # [1, 3]

Objects and References


In Python, everything is treated as an object, and variables do not store the actual data directly—instead,
they store a reference (or memory address) to the object. This concept is called objects and references.

Example:
a = [1, 2, 3]
b=a

the list [1, 2, 3] is created as an object in memory, and the variable a stores a reference to that object.
When you assign b = a, Python does not create a new list; instead, b is made to refer to the same object
that a is pointing to. This means both a and b are referencing the same list in memory. As a result, any
changes made using one variable (like [Link](4)) will also be reflected when accessing the list
through the other variable (b), because both refer to the same object.

Aliasing
Since variables refer to objects, if we assign one variable to another, both variables refer to the same
Object:

In this case, the state snapshot looks like this:

Because the same list has two different names, a and b, we say that it is aliased. Changes made with one
alias affect the other:

Python Programming (BBPYPB205), Department of CSE Module 2


27
Aliasing in Python
1. Aliasing occurs when two or more variables refer to the same object in memory.
Example:
2. a = [1, 2, 3]
3. b = a # b is an alias of a
Now, if we change b, the list a also changes because both point to the same list.
4. This behavior can sometimes be useful, as it allows multiple names to refer to the same data.
5. However, it can also be unexpected or undesirable, especially when you modify one variable
and accidentally change another.
6. It is safer to avoid aliasing when working with mutable objects such as:
●​ Lists
●​ Dictionaries
●​ Sets
●​ (Later, custom class objects)
7. For immutable objects (like strings and tuples), aliasing is not a problem, because:
●​ Their values cannot be changed once created.
●​ Therefore, no unexpected side effects occur when using an alias.
8. Example (immutable aliasing):
s1 = "hello"
s2 = s1
s2 = [Link]()
9. print(s1) # Output: hello
10. print(s2) # Output: HELLO
Here, s1 remains unchanged because strings are immutable.
11. Python sometimes automatically aliases immutable data (like strings or small numbers)
internally to save memory, since there’s no risk of accidental modification.

Cloning Lists
1. Sometimes, we may want to modify a list but also keep a copy of the original.
In such cases, we need to create a separate copy of the list — not just another reference to the
same list.
2. This process is called cloning, to avoid confusion with the term copy (which can also mean
reference).
3. The simplest way to clone a list in Python is by using the slice operator ([:]).
Python Programming (BBPYPB205), Department of CSE Module 2
28
4. Example:
​ a = [1, 2, 3]
b = a[:] # Cloning the list
print(b)
Output:
[1, 2, 3]
5. When you take a slice of a list, Python creates a new list object that contains the same elements
as the original.
6. Therefore, a and b are two different lists even though they contain the same data.
7. Relationship after cloning:
a → [1, 2, 3]
b → [1, 2, 3]
(Both lists look the same but are stored separately in memory.)
8. Now, you can change one list without affecting the other.
9. Example:
10. b[0] = 5
11. print(a)
12. print(b)
Output:
[1, 2, 3]
[5, 2, 3]
13. As seen, modifying b does not change a. This confirms that b is a clone a true copy of the list.

Lists and for Loops


1. The for loop in Python is commonly used to traverse (go through) all the elements of a list.
It allows us to perform actions on each element one by one.
2. General syntax:
3. for <variable> in <list>:
4. <body>
5. Example:
6. friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
7. for friend in friends:
8. print(friend)
Output:
Joe
Zoe
Brad
Angelina
Zuki

Python Programming (BBPYPB205), Department of CSE Module 2


29
Thandi
Paris
This reads like English:
“For every friend in the list of friends, print the name of the friend.”
Using Lists and Other Sequences in for Loops
4. You can use any list or sequence expression inside a for loop.
Example 1: Printing multiples of 3 between 0 and 19
for number in range(20):
if number % 3 == 0:
print(number)
Output:
0
3
6
9
12
15
18

Example 2: Using a list of fruits


for fruit in ["banana", "apple", "quince"]:
print("I like to eat " + fruit + "s!")
Output:
I like to eat bananas!
I like to eat apples!
I like to eat quinces!

Modifying List Elements Using a for Loop


5. Since lists are mutable, we can change their elements during traversal.
Example:
xs = [1, 2, 3, 4, 5]
for i in range(len(xs)):
xs[i] = xs[i] ** 2
print(xs)
Output:
[1, 4, 9, 16, 25]
Here, range(len(xs)) generates a sequence of indices from 0 to len(xs)-1.
6. In this loop, we need both:
●​ the value of each element (to square it), and

Python Programming (BBPYPB205), Department of CSE Module 2


30
●​ its index (to store the new value back in the list).

Using enumerate() for Easier Indexing


7. Python provides a built-in function enumerate() that returns both index and value during
traversal.
Example:
xs = [1, 2, 3, 4, 5]
for (i, val) in enumerate(xs):
xs[i] = val ** 2
print(xs)
Output:
[1, 4, 9, 16, 25]
8. The enumerate() function produces pairs of (index, value) for each element in the list.
9. Example (to see how enumerate works):
10. for (i, v) in enumerate(["banana", "apple", "pear", "lemon"]):
11. print(i, v)
Output:
0 banana
1 apple
2 pear
3 lemon

List Parameters
1. When a list is passed as an argument to a function, Python passes a reference, not a copy of the
list.
➤ This means the function receives an alias to the original list — both refer to the same object
in memory.
2. So, if the function modifies the list, the changes are visible outside the function as well.
Example:
def double_stuff(stuff_list):
"""Overwrite each element in a_list with double its value."""
for (index, stuff) in enumerate(stuff_list):
stuff_list[index] = 2 * stuff
things = [2, 5, 9]
double_stuff(things)
print(things)
Output:
[4, 10, 18]
Explanation:

Python Programming (BBPYPB205), Department of CSE Module 2


31
3. The variable things and the parameter stuff_list both refer to the same list object.
Therefore, any modification done to stuff_list inside the function directly affects things.
4. Before modification:
5. things → [2, 5, 9]
6. stuff_list → [2, 5, 9]
7. (both point to the same list)
8. After modification:
9. things → [4, 10, 18]
10. stuff_list → [4, 10, 18]
The change made inside the function reflects in the original list.
11. Since the list object is shared, if a function modifies the list parameter, the caller sees the
change.

List Methods
The dot operator (.) is used to access built-in methods of a list.
These methods perform specific operations on the list itself (like adding, removing,
sorting,etc.).
1. append()
• Usage: [Link](item)
• Function: Adds an item to the end of the list.
• Example:
• mylist = []
• [Link](5)
• [Link](27)
• [Link](3)
• [Link](12)
• print(mylist)
Output: [5, 27, 3, 12]
Python Programming (BBPYPB205), Department of CSE Module 2
32
2. insert()
• Usage: [Link](index, item)
• Function: Inserts an item at the specified index; shifts the remaining items to the right. •
Example:
• [Link](1, 12)
• print(mylist)
Output: [5, 12, 27, 3, 12]
3. count()
• Usage: [Link](item)
• Function: Returns how many times an item appears in the list.
• Example:
• [Link](12)
Output: 2
4. extend()
• Usage: [Link]([list])
• Function: Adds all elements of another list to the end of the current list. •
Example:
• [Link]([5, 9, 5, 11])
• print(mylist)
Output: [5, 12, 27, 3, 12, 5, 9, 5, 11]
5. index()
• Usage: [Link](item)
• Function: Returns the index of the first occurrence of the item.
• Example:
• [Link](9)
Output: 6

6. reverse()

Python Programming (BBPYPB205), Department of CSE Module 2


33
• Usage: [Link]()
• Function: Reverses the elements of the list in place.
• Example:
• [Link]()
• print(mylist)
Output: [11, 5, 9, 5, 12, 3, 27, 12, 5]
7. sort()
• Usage: [Link]()
• Function: Sorts the list in ascending order (default).
• Example:
• [Link]()
• print(mylist)
Output: [3, 5, 5, 5, 9, 11, 12, 12, 27]
8. remove()
• Usage: [Link](item)
• Function: Removes the first occurrence of the item from the list. •
Example:
• [Link](12)
• print(mylist)
Output: [3, 5, 5, 5, 9, 11, 12, 27]

2.3.15 Pure functions and modifiers


1. Difference Between Pure Functions and Modifiers
• Pure Function:
o Does not modify its arguments (no side effects).
o Works only with the data passed to it.
o Returns a new value or new list instead of changing the original. •
Modifier Function:
Python Programming (BBPYPB205), Department of CSE Module 2
34
●​ Changes (modifies) the list passed as an argument.
●​ The changes made are called side effects.
●​ Example: functions that directly modify the list (like using append,
remove, etc.).

[Link] Function
Example – double_stuff()
def double_stuff(a_list):
"""Return a new list which contains doubles of the elements in a_list."""
new_list = []
for value in a_list:
new_elem = 2 * value
new_list.append(new_elem)
return new_list

3. Explanation of the Code


• A new empty list new_list is created.
• Each element in a_list is multiplied by 2.
• The doubled value is added to new_list.
• Finally, the new list is returned, leaving the original list unchanged.

Example Output
things = [2, 5, 9]
more_things = double_stuff(things)
print(things) # Original list
print(more_things) # New list returned
Output:
[2, 5, 9]

Python Programming (BBPYPB205), Department of CSE Module 2


35
[4, 10, 18]

4. Important Observation

Even if you assign the result back to the same variable, it is still safe because the function returns a new
list, not modifying the old one.
things = [2, 5, 9]
things = double_stuff(things)
print(things)
Output:
[4, 10, 18]

Functions That Produce Lists


1. Introduction
• Some functions are designed to create and return new lists instead of modifying existing ones. •
Such functions generate a new list as their output (return value).
• These are usually pure functions they do not cause side effects.

[Link] Pattern to Create and Return a List


Whenever you want to write a function that produces a list, follow this pattern: 1.
Initialize an empty list → result = []
2. Loop through a sequence (like range() or a list).
3. Create or calculate a new element inside the loop.
4. Append that new element to result.
5. Return the result list at the end.

Initialize → Loop → Create → Append → Return

Python Programming (BBPYPB205), Department of CSE Module 2


36
3. Example: Function to Return Prime Numbers Less Than n
def primes_lessthan(n):
"""Return a list of all prime numbers less than n."""
result = [] # Step 1: Start with an empty list
for i in range(2, n): # Step 2: Loop through numbers 2 to n-1
if is_prime(i): # Step 3: Check if number is prime
[Link](i) # Step 4: Add it to the result list
return result # Step 5: Return the list
4. Example Execution
Suppose is_prime() is already defined.
print(primes_lessthan(10))
Output:
[2, 3, 5, 7]
5. Explanation
• The function checks each number from 2 to n-1.
• If it’s prime, that number is added to the result list.
• After the loop finishes, the final list of primes is returned

Step Action Code Example

1 Initialize empty list result = []

2 Loop through range for i in range(2, n):

3 Apply condition or operation if is_prime(i):

4 Append to list [Link](i)

5 Return final list return result

Strings and Lists


1. Relationship Between Strings and Lists
• Strings and lists are closely related in Python.

Python Programming (BBPYPB205), Department of CSE Module 2


37
• You can convert a string into a list or combine a list into a string using built-in methods.

2. split() Method – Converting String → List


• The split() method breaks a string into a list of words (substrings).
• By default, it uses whitespace (spaces, tabs, or newlines) as the separator.
Example:
song = "The rain in Spain..."
words = [Link]()
print(words)
Output:
['The', 'rain', 'in', 'Spain...']

3. Using a Delimiter in split()


• You can specify a custom delimiter (a string that marks where to split).
Example:
song = "The rain in Spain..."
print([Link]("ai"))

​ Output:
['The r', 'n in Sp', 'n...']
Note:
The delimiter (“ai”) does not appear in the result.

4. join() Method – Converting List → String


• The join() method does the reverse of split().
• It joins a list of strings into a single string, inserting a chosen separator (glue) between them.
Example:
words = ['The', 'rain', 'in', 'Spain...']

Python Programming (BBPYPB205), Department of CSE Module 2


38
glue = ";"
phrase = [Link](words)
print(phrase)
Output:
The;rain;in;Spain...
The original list words is not modified.

5. Using Different Types of Glue


Example 1: Using multi-character glue
" --- ".join(words)
Output:
The --- rain --- in --- Spain...'
Example 2: Using no glue (empty string)
"".join(words)
Output:
'TheraininSpain...

Lists and Range


1. The list() Function
• Python has a built-in function called list() that tries to convert any given value into a list.
Example:
letters = list("Crunchy Frog")
print(letters)
Output:
['C', 'r', 'u', 'n', 'c', 'h', 'y', ' ', 'F', 'r', 'o', 'g']
Here, the string "Crunchy Frog" is converted into a list of individual characters.

2. Converting Back to String


Python Programming (BBPYPB205), Department of CSE Module 2
39
• You can use the join() method to convert the list back into a string.
Example:
"".join(letters)
Output:
'Crunchy Frog'

[Link] range()
• The range() function represents a sequence of numbers, but it doesn’t generate all numbers
immediately.
• It creates a lazy object (a promise to produce numbers when needed).
• This is known as lazy evaluation — it saves memory and speeds up processing.
Example Function:
def f(n):
"""Find the first number between 101 and n that is divisible by 21"""
for i in range(101, n):
if i % 21 == 0:
return i
Testing it:
print(f(110)) # Output: 105
print(f(1000000000)) # Output: 105
Even though range(101, 1000000000) covers a huge range,
Python doesn’t create a list of all those numbers — it generates them one by one only when
needed.

4. Why Lazy Evaluation Matters

• Without lazy evaluation: Python would try to build a giant list in memory → �� crash! •
With lazy evaluation: Python only generates numbers on demand, so it runs efficiently.

5. Forcing range() to Produce a List

Python Programming (BBPYPB205), Department of CSE Module 2


40
• You can convert a lazy range into an actual list using list(range(...)).
Example:
print(range(10)) # Lazy promise
print(list(range(10))) # Converts to actual list
Output:
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

6. Fun Fact: YMMV


• YMMV stands for “Your Mileage May Vary” — meaning your results may differ. •
Before Python 3, range() was not lazy, so behavior could vary in older versions.

Looping and Lists

1. Purpose of Loops:
o Loops allow computers to repeat computations quickly and accurately.
o They are a core part of almost every program, especially when dealing with large data or
repetitive tasks.
2. Unnecessary Lists (Tip):
o Don’t create lists unless you actually need to store the data for later use.
o Lists take extra memory, so if data is only needed temporarily (like for summing
numbers), avoid storing it.
3. Example Programs:
o Two functions are shown — both generate 10 million random numbers and return
their sum.

Program 1: Using a List


def sum1():
xs = []
for i in range(10000000):

Python Programming (BBPYPB205), Department of CSE Module 2


41
num = [Link](1000)
[Link](num) # storing all numbers in a list
tot = sum(xs)
return tot
• Steps:
o Generates random numbers.
o Stores all numbers in a list (xs).
o Then calculates the sum using sum(xs).

Program 2: Without a List


def sum2():
tot = 0
for i in range(10000000):
num = [Link](1000)
tot += num # directly adds to total
return tot
• Steps:
o Generates random numbers.
o Directly adds each number to the total sum.
o Does not store numbers in memory.

4. Why Prefer the Second Version (sum2)


o Memory Efficiency:
▪ sum1() stores 10 million numbers → uses huge memory.
▪ sum2() doesn’t store → uses very little memory.
o Faster Execution:
▪ Less data storage = faster program.
o No Memory Errors:
Python Programming (BBPYPB205), Department of CSE Module 2
42
▪ Large lists can cause fatal memory errors, especially when memory is limited.

5. Practical Example (Files Analogy):


o When reading files:
▪ Whole file at once → loads everything into memory (can be risky for large
files).
▪ Line-by-line reading → reads only one line at a time (safe and memory
efficient).
o The line-by-line method is preferred for large files.

6. Key Takeaway:
o Use lists only if you need to reuse data later.
o If data is used immediately, process it directly inside the loop.
o Always think about memory usage and efficiency when working with loops.
2.3.20 Nested Lists
1. Definition:
o A nested list is a list that contains another list as one of its elements
It allows storing multiple levels of data inside one list
2. Example:
3. nested = ["hello", 2.0, 5, [10, 20]]
o This list has 4 elements:
▪ "hello" → string
▪ 2.0 → float
▪ 5 → integer
▪ [10, 20] → another list (this is the nested list)
4. Accessing the Nested List:
5. print(nested[3])
o Output: [10, 20]
o The element at index 3 is itself a list.
Python Programming (BBPYPB205), Department of CSE Module 2
43
6. Accessing Elements Inside the Nested List (Two Steps):
elem = nested[3] # get the nested list
print(elem[0]) # access its first element
o Output: 10

7. Accessing Elements in One Step (Combined):


print(nested[3][1])
o Output: 20
o Explanation:
▪ nested[3] → gets [10, 20]
▪ [1] → gets the second element (index 1) → 20

8. How It Works:
o The bracket operators ([]) are evaluated from left to right. o
So, nested[3][1] means:
▪ Access the 3rd element of nested.
▪ Then access the 1st element inside that nested list.

2.3.21 Matrices
1. Definition:
o A matrix is a rectangular arrangement of numbers in rows and columns.
o In Python, we can represent a matrix using nested lists — each inner list represents
one row of the matrix.
2. Example Matrix:

This matrix can be written in Python as:

Python Programming (BBPYPB205), Department of CSE Module 2


44
mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

3. Structure:
o The outer list → represents the matrix as a whole.
o Each inner list → represents one row.
So:
o mx[0] → [1, 2, 3] (1st row)
o mx[1] → [4, 5, 6] (2nd row)
o mx[2] → [7, 8, 9] (3rd row)

4. Accessing a Row:
print(mx[1])
Output:
[4, 5, 6]
mx[1] selects the 2nd row (since indexing starts from 0).

5. Accessing a Single Element (Double Index):


print(mx[1][2])
Output:
6​
o First index 1 → selects 2nd row [4, 5, 6]
o Second index 2 → selects 3rd element in that row → 6

6. How Indexing Works:


o mx[row][column]
o Example: mx[2][0] → 7 (3rd row, 1st column)

7. Alternate Representation:
Python Programming (BBPYPB205), Department of CSE Module 2
45
o Instead of rows, you could represent a matrix as a list of columns: o
mx_col = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
o Here, each inner list is a column instead of a row.
o (This approach is less common.)

8. Future Note:
o Later, we can represent matrices more efficiently using:
▪ Dictionaries (for sparse matrices)
▪ NumPy arrays (for numerical operations)
Key Takeaway:
• A matrix = list of lists in Python.
• First index = row, second index = column.
• Example:
mx[1][2] → element from 2nd row, 3rd column = 6

Python Programming (BBPYPB205), Department of CSE Module 2


46

You might also like