1 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
MODULE 2
SYLLABUS
CHAPTER 5
5.1 Strings:
5.1.1 Working with strings as single things
5.1.2 Working with the parts of a string
5.1.3 Length
5.1.4 Traversal and the for loop
5.1.5 Slices
5.1.6 String comparison
5.1.7 Strings are immutable
5.1.8 The in and not in operators
5.1.9 A find function
5.1.10 Looping and counting
5.1.11 Optional parameters
5.1.12 the built-in find method
5.1.13 the split method
5.1.14 cleaning up your strings
5.1.15 the string format method.
5. 2 Tuples:
5.2.1 Tuples are used for grouping data
5.2.2 Tuple assignment
5.2.3 Tuples as return values
5.2.4 Composability of Data Structures.
Dr. Taranum, Dept of AIML, KNSIT
2 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
5.3 Lists:
5.3.1 List values
5.3.2 Accessing elements
5.3.3 List length
5.3.4 List membership
5.3.5 List operations
5.3.6 List slices
5.3.7 Lists are mutable
5.3.8 List deletion
5.3.9 Objects and references
5.3.10 Aliasing
5.3.11 cloning lists
5.3.12 Lists and for loops
5.3.13 List parameters
5.3.14 List methods
5.3.15 Pure functions and modifiers
5.3.16 Functions that produce lists
5.3.17 Strings and lists
5.3.18 list and range
5.3.19 Nested lists
5.3.20 Matrices.
Chapter: 5.1, 5.2, 5.3
Dr. Taranum, Dept of AIML, KNSIT
3 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
5.1 Strings:
5.1.1 Working with strings as single things
5.1.2 Working with the parts of a string
5.1.3 Length
5.1.4 Traversal and the for loop
5.1.5 Slices
5.1.6 String comparison
5.1.7 Strings are immutable
5.1.8 The in and not in operators
5.1.9 A find function
5.1.10 Looping and counting
5.1.11 Optional parameters
5.1.12 the built-in find method
5.1.13 the split method
5.1.14 cleaning up your strings
5.1.15 the string format method
Ø A string is a sequence of characters. Python treats anything inside quotes as a string.
Ø This includes letters, numbers, and symbols.
Ø Python has no character data type so single character is a string of length 1
5.1.1 Working with strings as single things
In Python, sequences of characters are referred to as Strings. It used in Python to record text
information, such as names.
Python strings are "immutable" which means they cannot be changed after they are created.
Creating a String
Strings can be created using single quotes, double quotes, or even triple quotes.
# creating string
# with single Quotes
String = 'Hello Geek'
print("Creating string with single quotes :", String)
Dr. Taranum, Dept of AIML, KNSIT
4 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
# Creating String
# with double Quotes
String = "yes, I am Geek"
print("Creating String with double quotes :", String)
# Creating String
# with triple Quotes
String = '''yes, I am Geek'''
print("Creating String with triple quotes :", String)
Output:
Creating string with single quotes: Hello Geek
Creating String with double quotes: yes, I am Geek
Creating String with triple quotes: yes, I am Geek
Note: Be careful with quotes!
# creating string
# With single quotes
String = 'Yes' I am geek'
print(String)
Output:
File "<ipython-input-10-794636cfedda>", line 3
String = 'Yes' I am geek'
SyntaxError: invalid syntax
5.1.2 Working with the parts of a string
The indexing operator (Python uses square brackets to enclose the index) selects a single character
substring from a string:
>>> fruit = "banana"
>>> letter = fruit[1]
>>> print(letter)
Ø The expression fruit[1] selects character number 1 from fruit, and creates a new string
containing just this one character.
Dr. Taranum, Dept of AIML, KNSIT
5 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
Ø The variable letter refers to the result. When we display letter, we could get :
a
Ø The letter at subscript position zero of "banana" is b. So at position [1] we have the letter
a.
Ø If we want to access the zero-eth letter of a string, we just place 0, or any expression that
evaluates to 0, in between the brackets:
>>> letter = fruit[0]
>>> print(letter)
b
Ø The expression in brackets is called an index.
Ø An index specifies a member of an ordered collection, in this case the collection of
characters in the string.
Ø The index indicates which one you want, hence the name. It can be any integer expression.
Ø We can use enumerate to visualize the indices:
>>> fruit = "banana"
>>> list(enumerate(fruit))
[(0, 'b'), (1, 'a'), (2, 'n'), (3, 'a'), (4, 'n'), (5, 'a')]
Ø Note that indexing returns a string — Python has no special type for a single character. It
is just a string of length 1.
Ø The same indexing notation works to extract elements from a list:
>>> prime_numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
>>> prime_numbers[4]
11
>>> friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
>>> friends[3]
'Angelina'
5.1.3 Length
Ø The string len() function returns the length of the string.
Ø we will see how to find the length of a string using the string len() method.
Example:
s1 = "abcd"
print(len(s1))
Dr. Taranum, Dept of AIML, KNSIT
6 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
s2 = ""
print(len(s2))
s3 = "a"
print(len(s3))
Output:
4
0
1
Ø To get the last character, we have to subtract 1 from the length of word:
1 size = len(s1)
2 last = s1[size-1]
Ø Alternatively, we can use negative indices, which count backward from the end of the
string.
Ø The expression s1[-1] yields the last letter, s1[-2] yields the second to last, and so on.
5.1.4 Traversal and the for loop
String Traversal operations refers to process of one character at a time.
Often we start at the beginning, select each character in turn, do something to it, and continue until
the end.
Example:
Input: str = “GeeksforGeeks”
Output: G e e k s f o r G e e k s
Input: str = “Coder”
Output: C o d e r
Using For Loops
• Initialize a variable with the string you want to traverse.
• Use a for loop to iterate over each character in the string.
• In each iteration, the loop variable holds the current character.
• You can print or process the character within the loop.
For Example:
text = "Hello, World!"
Dr. Taranum, Dept of AIML, KNSIT
7 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
for char in text:
print(char)
Output:
H
e
l
l
o
,
W
o
r
l
d
!
5.1.5 Slices
String slicing in Python is a way to get specific parts of a string by using start, end and step values.
It’s especially useful for text manipulation and data parsing.
Syntax of String Slicing in Python
substring = s[start : end : step]
Parameters:
s: The original string.
start (optional): Starting index (inclusive). Defaults to 0 if omitted.
end (optional): Stopping index (exclusive). Defaults to the end of the string if omitted.
step (optional): Interval between indices. A positive value slices from left to right, while a negative
value slices from right to left. If omitted, it defaults to 1 (no skipping of characters).
Return Type: The result of a slicing operation is always a string (str type) that contains a subset
of the characters from the original string.
Example of string slicing:
Dr. Taranum, Dept of AIML, KNSIT
8 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
s = "Hello, Python!"
print(s[0:5])
Output:
Hello
In this example, we used the slice s[0:5] to obtain the substring "Hello" from the original string.
5.1.6 String comparison
Ø Python supports several operators for string comparison, including ==, !=, <, <=, >, and
>=.
Ø These operators allow for both equality and lexicographical (alphabetical order)
comparisons, which is useful when sorting or arranging strings.
Let’s start with a simple example to illustrate these operators.
s1 = "apple"
s2 = "banana"
# "apple" is not equal to "banana", therefore it is False
print(s1 == s2)
# "apple" is different from "banana", therefore it is True
print(s1 != s2)
# "apple" comes before "banana" lexicographically, therefore it is True
print(s1 < s2)
Output:
False
True
True
Explanation:
Ø == checks if two strings are identical.
Ø != checks if two strings differ.
Ø <, <=, >, >= perform lexicographical comparisons based on alphabetical order
== Operator for Equality Check
Ø The == operator is a simple way to check if two strings are identical. If both strings are
equal, it returns True; otherwise, it returns False.
Dr. Taranum, Dept of AIML, KNSIT
9 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
s1 = "Python"
s2 = "Python"
# Since both strings are identical, therefore it is True
print(s1 == s2)
Output:
True
Explanation: In this example, since s1 and s2 have the same characters in the same order, so ==
returns True.
!= Operator for Inequality Check
Ø The != operator helps to verify if two strings are different. If the strings are different then
it will return True, otherwise returns False.
s1 = "Python"
s2 = "Java"
# "Python" is different from "Java", therefore it is True
print(s1 != s2)
Output:
True
Explanation: Here, != checks that s1 and s2 are not the same, so it returns True.
Lexicographical Comparison
Ø Lexicographical comparison checks if one string appears before or after another in
alphabetical order. This is especially useful for sorting.
s1 = "apple"
s2 = "banana"
# "apple" appears before "banana" alphabetically, therefore it is True
print(s1 < s2)
# "banana" comes after "apple", therefore it is True
print(s2 > s1)
Output:
True
Dr. Taranum, Dept of AIML, KNSIT
10 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
True
Explanation: The < and > operators are used to find the order of s1 and s2 lexicographically. This
method ideal for sorting and alphabetical comparisons.
Case-Insensitive Comparison
Ø Strings in Python can be compared case-insensitively by converting both strings to either
lowercase or uppercase.
s1 = "Apple"
s2 = "apple"
# Both strings are same ignoring case, therefore it is True
print([Link]() == [Link]())
Output:
True
Explanation: Converting both strings to lowercase (or uppercase) before comparison
5.1.7 Strings are immutable
Strings in Python are "immutable" which means they can not be changed after they are created.
Some other immutable data types are integers, float, boolean, etc.
For example:
1 greeting = "Hello, world!"
2 greeting[0] = 'J' # ERROR!
3 print(greeting)
Instead of producing the output Jello, world!, this code produces the runtime error TypeError: 'str'
object does not support item assignment.
Strings are immutable, which means you can’t change an existing string. The best you can do is
create a new string that is a variation on the original:
1 greeting = "Hello, world!"
2 new_greeting = "J" + greeting[1:]
3 print(new_greeting)
The solution here is to concatenate a new first letter onto a slice of greeting. This operation has no
effect on the original string.
Dr. Taranum, Dept of AIML, KNSIT
11 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
5.1.8 The in and not in operators
The in operator tests for membership. When both of the arguments to in are strings, in checks
whether the left argument is a substring of the right argument.
>>> "p" in "apple"
True
>>> "i" in "apple"
False
>>> "ap" in "apple"
True
>>> "pa" in "apple"
False
Note that a string is a substring of itself, and the empty string is a substring of any other
string.
>>> "a" in "a"
True
>>> "apple" in "apple"
True
>>> "" in "a"
True
>>> "" in "apple"
True
The not in operator returns the logical opposite results of in:
>>> "x" not in "apple"
True
Combining the in operator with string concatenation using +, we can write a function that removes
all the vowels from a string:
1 def remove_vowels(phrase):
2 vowels = "aeiou"
3 string_sans_vowels = ""
Dr. Taranum, Dept of AIML, KNSIT
12 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
4 for letter in phrase:
5 if [Link]() not in vowels:
6 string_sans_vowels += letter
7 return string_sans_vowels
Important to note is the [Link]() in line 5, without it, any uppercase vowels would not be
removed.
5.1.9 A find function
Ø The find() method finds the first occurrence of the specified value.
Ø The find() method returns -1 if the value is not found.
Ø The find() method is almost the same as the index() method, the only difference is that the
index() method raises an exception if the value is not found. (See example below)
Syntax
[Link](value, start, end)
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string
Example: Where in the text is the first occurrence of the letter "e"?:
txt = "Hello, welcome to my world."
x = [Link]("e")
print(x)
Output: 1
Where in the text is the first occurrence of the letter "e" when you only search between
position 5 and 10?:
txt = "Hello, welcome to my world."
x = [Link]("e", 5, 10)
print(x)
Output: 8
If the value is not found, the find() method returns -1, but the index() method will raise an
exception:
txt = "Hello, welcome to my world."
Dr. Taranum, Dept of AIML, KNSIT
13 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
print([Link]("q"))
print([Link]("q"))
Output:
-1
Traceback (most recent call last):
File "demo_ref_string_find_vs_index.py", line 4 in <module>
print([Link]("q"))
ValueError: substring not found
5.1.10 Looping and counting
In Python, looping and counting can be achieved using various methods, primarily
involving for and while loops.
1. Counting with a for loop and range():
The range() function generates a sequence of numbers, which can be iterated over using a for loop
to count a specific number of times.
Example:
# Count from 0 to 4 (5 iterations)
for i in range(5):
print(f"Iteration {i}")
# Count from 1 to 5
for i in range(1, 6): # The stop value is exclusive
print(f"Number: {i}")
# Count with a step (e.g., even numbers)
for i in range(0, 10, 2):
print(f"Even number: {i}")
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Dr. Taranum, Dept of AIML, KNSIT
14 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
Iteration 4
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Even number: 0
Even number: 2
Even number: 4
Even number: 6
Even number: 8
2. Counting with a while loop:
A while loop continues as long as a specified condition is true. A counter variable is typically
initialized before the loop and incremented within it.
Example:
count = 0
while count < 5:
print(f"Current count: {count}")
count += 1 # Increment the counter
Output:
Current count: 0
Current count: 1
Current count: 2
Current count: 3
Current count: 4
5.1.11 Optional parameters
The find() function in Python strings has two optional parameters: start and end.
These parameters allow you to specify a sub-range within the string where the search for the
substring should occur.
Dr. Taranum, Dept of AIML, KNSIT
15 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
start:
This optional integer parameter indicates the starting index position (inclusive) from where the
search for the substring should begin. If omitted, the search starts from the beginning of the string
(index 0).
end:
This optional integer parameter indicates the ending index position (exclusive) where the search
for the substring should stop. If omitted, the search continues until the end of the string.
Examples:
Without optional parameters:
my_string = "hello world"
index = my_string.find("o")
print(index) # Output: 4 (first 'o' in "hello")
Output: 4
With start parameter:
my_string = "hello world"
index = my_string.find("o", 5) # Search for 'o' starting from index 5
print(index) # Output: 7 (first 'o' in "world")
Output: 7
With start and end parameters:
my_string = "hello world"
index = my_string.find("o", 0, 5) # Search for 'o' between index 0 (inclusive) and 5 (exclusive)
print(index) # Output: 4 (first 'o' in "hello")
Output: 4
5.1.12 The built-in find method
The built-in find() method in Python is a string method used to locate the first occurrence of a
specified substring within a given string.
Syntax:
[Link](substring, start, end)
Dr. Taranum, Dept of AIML, KNSIT
16 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
start:
This optional integer parameter indicates the starting index position (inclusive) from where the
search for the substring should begin. If omitted, the search starts from the beginning of the string
(index 0).
end:
This optional integer parameter indicates the ending index position (exclusive) where the search
for the substring should stop. If omitted, the search continues until the end of the string.
Functionality:
Search for Substring:
The find() method searches for the substring within the string.
Returns Index:
If the substring is found, it returns the lowest index (the starting position) of its first occurrence.
Returns -1 if Not Found:
If the substring is not found within the specified range, the method returns -1.
Case-Sensitive:
The find() method is case-sensitive, meaning "hello" and "Hello" are treated as different strings.
Example:
text = "Hello, world! Welcome to Python."
# Find the index of "world"
index1 = [Link]("world")
print(f"Index of 'world': {index1}")
# Find the index of "Python" starting from index 20
index2 = [Link]("Python", 20)
print(f"Index of 'Python' from index 20: {index2}")
# Try to find a substring that doesn't exist
index3 = [Link]("java")
print(f"Index of 'java': {index3}")
# Find a substring within a specific range
index4 = [Link]("come", 10, 20)
Dr. Taranum, Dept of AIML, KNSIT
17 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
print(f"Index of 'come' between index 10 and 20: {index4}")
Output:
Index of 'world': 7
Index of 'Python' from index 20: 25
Index of 'java': -1
Index of 'come' between index 10 and 20: -1
5.1.13 The split method
The split() method in Python is a built-in string method used to break a string into a list of
substrings. It operates based on a specified delimiter.
Syntax:
[Link](separator, maxsplit)
Parameters:
separator (optional):
Ø This argument specifies the delimiter used to split the string.
Ø If separator is not provided or is None, the string is split by any whitespace characters
(spaces, tabs, newlines), and empty strings resulting from the split are discarded.
maxsplit (optional):
Ø This argument specifies the maximum number of splits to perform.
Ø If maxsplit is provided, the list will contain at most maxsplit + 1 elements.
Ø If maxsplit is not provided or is -1, there is no limit on the number of splits.
Return Value:
The split() method returns a list of substrings.
Examples:
Splitting by default whitespace:
text = "This is a sample string."
words = [Link]()
print(words)
Output: ['This', 'is', 'a', 'sample', 'string.']
Splitting by a specific character:
data = "apple,banana,cherry"
Dr. Taranum, Dept of AIML, KNSIT
18 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
fruits = [Link](',')
print(fruits)
Output: ['apple', 'banana', 'cherry']
Splitting with maxsplit:
sentence = "one two three four five"
parts = [Link](' ', 2)
print(parts)
Output: ['one', 'two', 'three four five']
5.1.14 Cleaning up your strings
Cleaning up strings in Python involves various operations to remove unwanted characters,
normalize case, or standardize formatting. Here are common methods for string cleanup:
1. Removing Whitespace:
strip(): Removes leading and trailing whitespace characters (spaces, tabs, newlines) from a string.
text = " Hello World! "
cleaned_text = [Link]()
print(cleaned_text) # Output: "Hello World!"
lstrip(): Removes leading whitespace characters from the left side of the string.
rstrip(): Removes trailing whitespace characters from the right side of the string.
2. Changing Case:
lower(): Converts all characters in a string to lowercase.
text = "PyThOn PrOgRaMmInG"
lower_text = [Link]()
print(lower_text) # Output: "python programming"
upper(): Converts all characters in a string to uppercase.
capitalize(): Capitalizes the first character of the string and converts the rest to lowercase.
title(): Converts the string to title case, where the first letter of each word is capitalized.
3. Removing Specific Characters or Substrings:
replace(): Replaces all occurrences of a specified substring with another substring.
Dr. Taranum, Dept of AIML, KNSIT
19 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
text = "This string has dashes-and-more."
no_dashes = [Link]("-", "")
print(no_dashes) # Output: "This string has dashesandmore."
strip(characters): Removes a specified set of characters from the leading and trailing ends of the
string.
text = "///data///"
cleaned_text = [Link]('/')
print(cleaned_text) # Output: "data"
Regular Expressions (re module): For more complex pattern-based removal, such as removing
special characters, numbers, or URLs.
import re
text = "Text with @symbols and #hashtags!"
cleaned_text = [Link](r'[@#]', '', text)
print(cleaned_text) # Output: "Text with symbols and hashtags!"
5.1.15 The string format method
Ø The [Link]() method in Python provides a versatile way to format strings by embedding
values into a template string.
Ø This method allows for clear and readable string construction, especially when dealing with
multiple variables or complex formatting requirements.
Basic Usage:
Ø The format() method uses curly braces {} as placeholders within a string.
Ø When the method is called, the values passed as arguments are inserted into these
placeholders in the order they appear.
name = "Alice"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
Output:
My name is Alice and I am 30 years old.
Positional and Keyword Arguments:
Positional arguments: Values are inserted based on their order in the format() call.
Dr. Taranum, Dept of AIML, KNSIT
20 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
Indexed arguments: You can specify the index of the argument within the curly braces to control
the insertion order.
Keyword arguments: You can assign names to placeholders within the string and then pass
corresponding keyword arguments to format().
# Indexed arguments
message_indexed = "The first value is {0}, and the second is {1}.".format("apple", "banana")
print(message_indexed)
Output:
The first value is apple, and the second is banana.
# Keyword arguments
message_keyword = "My name is {name} and I live in {city}.".format(name="Bob", city="New
York")
print(message_keyword)
Output: My name is Bob and I live in New York.
Advanced Formatting:
The format() method supports various formatting options within the curly braces, including:
Alignment: Left (<), right (>), or center (^) alignment within a specified width.
Number formatting: Control decimal places, add thousands separators, and specify number bases
(e.g., binary, hexadecimal).
Type conversion: Convert values to specific types (e.g., character, decimal, scientific notation).
# Number formatting
pi_value = 3.14159265
formatted_pi = "The value of pi is {:.2f}.".format(pi_value) # Two decimal places
print(formatted_pi)
Output: The value of pi is 3.14.
# Alignment
aligned_text = "{:<10} | {:>10}".format("Left", "Right")
print(aligned_text)
Output: Left | Right
Dr. Taranum, Dept of AIML, KNSIT
21 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
5. 2 Tuples:
5.2.1 Tuples are used for grouping data
5.2.2 Tuple assignment
5.2.3 Tuples as return values
5.2.4 Composability of Data Structures.
5.2.1 Tuples are used for grouping data
Ø A tuple is an ordered, immutable (unchangeable) collection of items.
Ø Defined using parentheses ().
Ø Can store heterogeneous data (different data types: int, float, string, etc.).
Ø Useful when you want to keep data together but don’t need to modify it.
Example 1: Grouping related values
# Grouping student data into a tuple
student = ("Alice", 21, "Computer Science")
print(student)
print("Name:", student[0])
print("Age:", student[1])
print("Course:", student[2])
OUTPUT
('Alice', 21, 'Computer Science')
Name: Alice
Age: 21
Course: Computer Science
Example 2: Tuple as return type (grouping multiple outputs)
def min_max(numbers):
return (min(numbers), max(numbers)) # returning as a tuple
result = min_max([10, 5, 20, 7])
print("Minimum:", result[0])
print("Maximum:", result[1])
Dr. Taranum, Dept of AIML, KNSIT
22 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
OUTPUT
Minimum: 5
Maximum: 20
Example 3: Nested grouping
# Grouping students in a class
classroom = [
("Alice", 21, "CS"),
("Bob", 22, "Math"),
("Charlie", 20, "Physics")
]
print(classroom[0]) # ('Alice', 21, 'CS')
print(classroom[1][0]) # 'Bob'
OUTPUT
('Alice', 21, 'CS')
Bob
5.2.2 Tuple assignment
Ø Tuple assignment in Python is a neat way of assigning multiple values to multiple variables
at once using tuples.
Ø Tuple assignment is a way to unpack values from a tuple (or iterable) directly into
variables in a single statement.
Ø It makes code cleaner, especially when dealing with multiple values.
Example:
# Normal assignment
x = 10
y = 20
# Tuple assignment
(x, y) = (10, 20)
print(x) # 10
print(y) # 20
Dr. Taranum, Dept of AIML, KNSIT
23 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
Here (x, y) is a tuple of variables, and (10, 20) is a tuple of values.
Without parentheses (Python allows it)
x, y = 10, 20
print(x, y) # 10 20
Swapping values (common use case)
a, b = 5, 7
a, b = b, a # swap
print(a, b) # 7 5
Using with * (tuple unpacking with variable length)
a, *b, c = (10, 20, 30, 40, 50)
print(a) # 10
print(b) # [20, 30, 40]
print(c) # 50
5.2.3 Tuples as return values
In Python, a function can return multiple values by packing them into a tuple. This is one of the
most common uses of tuples.
Example 1: Returning a Tuple
def min_max(numbers):
smallest = min(numbers)
largest = max(numbers)
return (smallest, largest) # returns a tuple
Calling the function:
nums = [3, 7, 2, 9, 5]
result = min_max(nums)
print(result) # (2, 9)
print(type(result)) # <class 'tuple'>
Example 2: Tuple Unpacking
You can directly unpack the tuple into multiple variables:
Dr. Taranum, Dept of AIML, KNSIT
24 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
nums = [3, 7, 2, 9, 5]
low, high = min_max(nums) # tuple unpacking
print("Lowest:", low)
print("Highest:", high)
OUTPUT
Lowest: 2
Highest: 9
Example 3: Returning Multiple Computations
def calculate(a, b):
add = a + b
sub = a - b
mul = a * b
div = a / b if b != 0 else None
return add, sub, mul, div # tuple is created automatically
# Unpack results
s, d, m, q = calculate(10, 2)
print("Sum:", s)
print("Diff:", d)
print("Prod:", m)
print("Quot:", q)
OUTPUT:
Sum: 12
Diff: 8
Prod: 20
Quot: 5.0
Dr. Taranum, Dept of AIML, KNSIT
25 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
5.2.4 Composability of Data Structures
Ø Composability of data structures in Python means combining different data structures
together to build more complex or hierarchical structures.
Ø Python’s built-in data structures (lists, tuples, sets, dictionaries) are highly composable,
meaning they can be nested or used inside one another
Examples of Composability
1 List of Tuples
Useful for storing pairs of values, like coordinates or student records:
students = [("Alice", 85), ("Bob", 90), ("Charlie", 78)]
Here each tuple stores a (name, score), and the list holds multiple records.
2 Dictionary of Lists
Useful for grouping multiple values under a single key:
grades = {
"Math": [90, 85, 92],
"Science": [88, 79, 95],
"English": [75, 80, 85]
}
Here Each key maps to a list of marks.
3 List of Dictionaries
Useful when you want structured records:
employees = [
{"id": 1, "name": "John", "role": "Manager"},
{"id": 2, "name": "Sara", "role": "Developer"}
]
Set of Tuples
Sets require elements to be hashable, so you can use tuples:
coordinates = {(1, 2), (3, 4), (5, 6)}
Dr. Taranum, Dept of AIML, KNSIT
26 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
5.3 Lists:
5.3.1 List values
5.3.2 Accessing elements
5.3.3 List length
5.3.4 List membership
5.3.5 List operations
5.3.6 List slices
5.3.7 Lists are mutable
5.3.8 List deletion
5.3.9 Objects and references
5.3.10 Aliasing
5.3.11 cloning lists
5.3.12 Lists and for loops
5.3.13 List parameters
5.3.14 List methods
5.3.15 Pure functions and modifiers
5.3.16 Functions that produce lists
5.3.17 Strings and lists
5.3.18 list and range
5.3.19 Nested lists
5.3.20 Matrices.
5.3 Lists
Ø A list is an ordered collection of values. The values that make up a list are called its
elements, or its items. We will use the term element or item to mean the same thing.
Ø Lists are similar to strings, which are ordered collections of characters, except that the
elements of a list can be of any type.
Ø Lists and strings—and other collections that maintain the order of their items— are called
sequences.
Dr. Taranum, Dept of AIML, KNSIT
27 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
5.3.1 List values
There are several ways to create a new list; the simplest is to enclose the elements in square
brackets ([ and ]):
Example:
1 numbers = [10, 20, 30, 40]
2 words = ["spam", "bungee", "swallow"]
Ø The first example is a list of four integers.
Ø The second is a list of three strings. The elements of a list don’t have to be the same type.
The following list contains a string, a float, an integer, and (amazingly) another list:
1 stuffs = ["hello", 2.0, 5, [10, 20]]
Ø A list within another list is said to be nested.
Ø Finally, a list with no elements is called an empty list, and is denoted [].
We have already seen that we can assign list values to variables or pass lists as parameters to
functions:
1 >>> vocabulary = ["apple", "cheese", "dog"]
2 >>> numbers = [17, 123]
3 >>> an_empty_list = []
4 >>> print(vocabulary, numbers, an_empty_list)
5 ["apple", "cheese", "dog"] [17, 123] []
5.3.2 Accessing elements
In Python, lists are ordered collections, and you can access their elements using indexing or slicing.
1. Access by Index
Ø Indexing starts from 0 for the first element.
Ø Negative indices count from the end.
Example:
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # First element → apple
print(fruits[2]) # Third element → cherry
print(fruits[-1]) # Last element → date
print(fruits[-2]) # Second last element → cherry
Dr. Taranum, Dept of AIML, KNSIT
28 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
2. Access by Slicing
• Syntax: list[start:end:step]
• start = index to begin (inclusive)
• end = index to stop (exclusive)
• step = jump size (default 1)
Example:
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[2:]) # ['cherry', 'date']
print(fruits[::2]) # ['apple', 'cherry'] (every 2nd element)
3. Access in a Loop
Example:
for fruit in fruits:
print(fruit)int(fruits[::-1]) # ['date', 'cherry', 'banana', 'apple'] (reversed list)
4. Access Multiple Elements with List Comprehension
Example:
indices = [0, 2, -1]
selected = [fruits[i] for i in indices]
print(selected) # ['apple', 'cherry', 'date']
5.3.3 List length
In Python, you can find the length of a list (i.e., the number of elements it contains) using the built-
in len() function.
Example:
# A list of numbers
numbers = [10, 20, 30, 40, 50]
# Get length of list
length = len(numbers)
print("Length of the list is:", length)
Dr. Taranum, Dept of AIML, KNSIT
29 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
Output:
Length of the list is: 5
$ Works for any list, whether it contains numbers, strings, or even nested lists.
#
⬛
5.3.4 List membership
In Python, list membership means checking whether an element is present in a list or not.
We use the operators in and not in for membership testing.
Example 1: Using in
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("mango" in fruits) # False
Example 2: Using not in
numbers = [1, 2, 3, 4, 5]
print(10 not in numbers) # True
print(3 not in numbers) # False
Example 3: Using in conditional statements
colors = ["red", "blue", "green"]
if "blue" in colors:
print("Blue is available!")
else:
print("Blue is not available.")
Ø in returns True if the element exists in the list.
Ø not in returns True if the element does not exist in the list.
5.3.5 List operations
In Python, lists are one of the most commonly used data structures.
They are mutable (can be changed) and allow duplicate elements. You can perform many
operations on lists:
Basic List Operations
# Creating a list
numbers = [10, 20, 30, 40, 50]
Dr. Taranum, Dept of AIML, KNSIT
30 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
# 1. Accessing elements
print(numbers[0]) # First element → 10
print(numbers[-1]) # Last element → 50
# 2. Modifying elements
numbers[1] = 25
print(numbers) # [10, 25, 30, 40, 50]
# 3. Adding elements
[Link](60) # Add at end
[Link](2, 15) # Insert at index 2
print(numbers) # [10, 25, 15, 30, 40, 50, 60]
# 4. Removing elements
[Link](30) # Removes first occurrence of 30
popped = [Link]() # Removes last element
print(popped) # 60
del numbers[0] # Delete element at index 0
print(numbers)
# 5. Length of list
print(len(numbers)) # 5
# 6. Checking membership
print(40 in numbers) # True
print(100 not in numbers) # True
# 7. Concatenation & repetition
list1 = [1, 2]
list2 = [3, 4]
print(list1 + list2) # [1, 2, 3, 4]
print(list1 * 3) # [1, 2, 1, 2, 1, 2]
# 8. Slicing
print(numbers[1:4]) # Sublist from index 1 to 3
Dr. Taranum, Dept of AIML, KNSIT
31 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
print(numbers[::-1]) # Reverse the list
5.3.6 List slices
In Python, list slicing allows you to extract parts of a list (a sublist) using the : operator inside
square brackets [].
General Syntax:
list[start:end:step]
start → index where the slice begins (inclusive, default = 0)
end → index where the slice ends (exclusive, default = len(list))
step → how many items to skip (default = 1)
Examples:
# Original list
nums = [10, 20, 30, 40, 50, 60, 70]
# Basic slicing
print(nums[1:4]) # [20, 30, 40] (from index 1 to 3)
print(nums[:3]) # [10, 20, 30] (start omitted, goes from 0 to 2)
print(nums[3:]) # [40, 50, 60, 70] (end omitted, goes to end)
# Using step
print(nums[::2]) # [10, 30, 50, 70] (every 2nd element)
print(nums[1:6:2]) # [20, 40, 60] (from index 1 to 5, step 2)
# Negative indices
print(nums[-3:]) # [50, 60, 70] (last 3 elements)
print(nums[:-2]) # [10, 20, 30, 40, 50] (all except last 2)
# Reverse a list
print(nums[::-1]) # [70, 60, 50, 40, 30, 20, 10]
Key points:
Ø start is inclusive, end is exclusive.
Ø Leaving start or end blank means "from the beginning" or "till the end".
Ø Negative indices count from the end (-1 = last element).
Ø step can be negative for reverse slicing.
Dr. Taranum, Dept of AIML, KNSIT
32 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
5.3.7 Lists are mutable
Mutability means that after a list is created, you can change its elements, add new ones, or
remove existing ones without creating a new list object.
Example 1: Changing elements
nums = [10, 20, 30, 40]
nums[1] = 99 # modify element at index 1
print(nums) # [10, 99, 30, 40]
Example 2: Adding elements
nums = [1, 2, 3]
[Link](4) # add at end
print(nums) # [1, 2, 3, 4]
[Link](1, 99) # insert at index 1
print(nums) # [1, 99, 2, 3, 4]
Example 3: Removing elements
nums = [5, 6, 7, 8]
[Link](6) # remove by value
print(nums) # [5, 7, 8]
[Link](1) # remove by index
print(nums) # [5, 8]
Example 4: In-place modifications
nums = [1, 2, 3, 4]
[Link]() # sorts the same list
print(nums) # [1, 2, 3, 4] (sorted ascending)
[Link]() # reverses in place
print(nums) # [4, 3, 2, 1]
Dr. Taranum, Dept of AIML, KNSIT
33 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
5.3.8 List deletion
In Python, you can delete elements from a list (or even the whole list) in several ways because lists
are mutable.
1. Using del statement
Removes element(s) at a specific index or slice.
nums = [10, 20, 30, 40, 50]
del nums[2] # delete element at index 2
print(nums) # [10, 20, 40, 50]
del nums[1:3] # delete a slice (indexes 1 to 2)
print(nums) # [10, 50]
del nums[:] # delete all elements (empty list)
print(nums) # []
2. Using remove()
Ø Removes first occurrence of a value (not index).
Ø Raises ValueError if the value is not found.
nums = [1, 2, 3, 2, 4]
[Link](2)
print(nums) # [1, 3, 2, 4] (first 2 removed)
3. Using pop()
Removes and returns element at a given index (default = last).
nums = [10, 20, 30, 40]
x = [Link](2)
print(x) # 30
print(nums) # [10, 20, 40]
y = [Link]() # removes last element
print(y) # 40
4. Using clear()
Removes all elements, leaves an empty list.
nums = [1, 2, 3, 4]
Dr. Taranum, Dept of AIML, KNSIT
34 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
[Link]()
print(nums) # []
5. Deleting the whole list
Using del on the variable removes the entire list object.
nums = [10, 20, 30]
del nums
# print(nums) # + Error: NameError (list no longer exists)
$
#
⬛ Summary:
del → delete by index/slice, or whole list.
remove() → delete by value.
pop() → delete by index (and get the value).
clear() → delete all elements (empty list).
5.3.9 Objects and references
1 Objects in Python
In Python, everything is an object: numbers, strings, lists, functions, even classes.
An object is just a chunk of memory that contains:
Type → what kind of object it is (int, str, list, etc.).
Value → the data stored inside it.
Reference count → how many variables (names) are pointing to it.
Example:
x = 10
Here, 10 is an object of type int.
The variable x is just a name (label) pointing to that object.
2. References in Python
A reference is like an arrow pointing to an object.
When you do:
a = [1, 2, 3]
b=a
Dr. Taranum, Dept of AIML, KNSIT
35 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
a refers to a list object [1, 2, 3].
b is another reference pointing to the same object.
There is only one list object in memory.
Check this with id() (gives memory address-like identity):
print(id(a))
print(id(b))
Both will print the same value → same object.
3. Mutable vs Immutable Objects
Immutable objects (like int, float, str, tuple):
Their value cannot be changed.
Assigning a new value creates a new object.
x=5
y=x
x=x+1
print(x, y) # 6, 5 → x now points to a new object (6), y still points to old one (5).
Mutable objects (like list, dict, set):
Their content can be changed without creating a new object.
a = [1, 2, 3]
b=a
[Link](4)
print(a) # [1, 2, 3, 4] → both a and b see the change
4. Copy vs Reference
If you want a new object instead of another reference:
import copy
a = [1, 2, 3]
b = a[:] # shallow copy
c = [Link](a) # deep copy
[Link](4)
Dr. Taranum, Dept of AIML, KNSIT
36 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3] (separate object)
print(c) # [1, 2, 3] (separate object)
In summary:
Ø An object = data + type stored in memory.
Ø A reference = a name (or pointer) that refers to an object.
Ø Variables don’t “hold” values directly, they reference objects
5.3.10 Aliasing
Aliasing happens when two or more variables reference (point to) the same object in memory.
Changing the object through one variable will affect the other, because they are just different
names (aliases) for the same object.
Example with Mutable Objects
a = [1, 2, 3]
b = a # b is an alias of a
[Link](4)
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3, 4]
Here, a and b are aliases → both point to the same list object.
Modifying via b affects a.
Example with Immutable Objects
x = 10
y = x # y is an alias of x, both point to 10
x = x + 1 # creates a new int object 11
print(x) # 11
print(y) # 10
Since integers are immutable, changing x makes it point to a new object, so y is unaffected.
Avoiding Aliasing (Copy Instead)
Sometimes aliasing is unwanted. To create a copy instead of an alias:
Dr. Taranum, Dept of AIML, KNSIT
37 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
For lists:
import copy
a = [1, 2, 3]
b = a[:] # shallow copy
c = [Link](a) # deep copy
[Link](4)
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3] (separate object)
print(c) # [1, 2, 3] (separate object)
Visualizing Aliasing
Think of aliases as nicknames for the same person:
If you change the person (mutable object), all nicknames see the change.
If you give the nickname to a new person (immutable object assignment), only that name changes.
5.3.11 Cloning lists
Cloning a list means making a new copy of it, instead of creating an alias.
If you just assign (b = a), both names refer to the same list → aliasing.
If you clone, you create a new list object with the same contents.
◆ Ways to Clone a List
1. Using slicing
a = [1, 2, 3]
b = a[:] # clone
[Link](4)
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3] (separate copy)
2. Using list() constructor
a = [1, 2, 3]
b = list(a)
[Link](4)
Dr. Taranum, Dept of AIML, KNSIT
38 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3]
3. Using .copy() method
a = [1, 2, 3]
b = [Link]()
[Link](4)
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3]
4. Using copy module
Shallow copy (copies outer list, not inner lists):
import copy
a = [[1, 2], [3, 4]]
b = [Link](a) # shallow clone
a[0].append(99)
print(a) # [[1, 2, 99], [3, 4]]
print(b) # [[1, 2, 99], [3, 4]] (inner lists shared!)
Deep copy (copies everything, including inner lists):
import copy
a = [[1, 2], [3, 4]]
b = [Link](a)
a[0].append(99)
print(a) # [[1, 2, 99], [3, 4]]
print(b) # [[1, 2], [3, 4]] (completely independent)
5.3.12 Lists and for loops
Syntax:
for <VARIABLE> in <LIST>:
<BODY>
Dr. Taranum, Dept of AIML, KNSIT
39 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
1. Iterating over a list
You can loop through a list directly:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
− Output:
–
apple
banana
cherry
2. Iterating with indexes
Sometimes you want both the index and the value. Use range() or enumerate():
Using range(len(...))
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i, fruits[i])
– Output:
−
0 apple
1 banana
2 cherry
Using enumerate() (cleaner)
for i, fruit in enumerate(fruits):
print(i, fruit)
3. Modifying list elements in a loop
You can change list items by index:
numbers = [1, 2, 3, 4]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
print(numbers) # [2, 4, 6, 8]
Dr. Taranum, Dept of AIML, KNSIT
40 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
4. Looping with conditions
numbers = [10, 15, 20, 25]
for n in numbers:
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")
5. List comprehension (short-hand loop)
Instead of writing a full loop, you can create a new list in one line:
numbers = [1, 2, 3, 4, 5]
squares = [n*n for n in numbers]
print(squares) # [1, 4, 9, 16, 25]
$
#
⬛ Summary:
for item in list: → iterate directly.
for i in range(len(list)): → iterate by index.
enumerate(list) → index + value.
Modify list items by index in a loop.
Use list comprehensions for concise list creation.
5.3.13 List parameters
Ø Passing a list as an argument actually passes a reference to the list, not a copy or clone of
the list.
Ø So, parameter passing creates an alias for you: the caller has one variable referencing the
list, and the called function has an alias, but there is only one underlying list object.
1. Passing a List to a Function
In Python, lists are passed by reference (not by value).
That means if you modify the list inside the function, the change is visible outside too.
Example:
def modify_list(mylist):
[Link](100)
Dr. Taranum, Dept of AIML, KNSIT
41 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
numbers = [1, 2, 3]
modify_list(numbers)
print(numbers) # [1, 2, 3, 100]
–
− The original list changed, because both numbers and mylist refer to the same object.
2. Preventing Changes (Cloning inside function)
If you don’t want the original list to change, make a copy:
def safe_modify(mylist):
copy_list = mylist[:] # clone
copy_list.append(100)
return copy_list
numbers = [1, 2, 3]
new_list = safe_modify(numbers)
print(numbers) # [1, 2, 3] (unchanged)
print(new_list) # [1, 2, 3, 100]
3. Using Lists as Parameters
You can:
Read values
def print_list(lst):
for item in lst:
print(item)
print_list([10, 20, 30])
Modify values
def double_list(lst):
for i in range(len(lst)):
lst[i] *= 2
nums = [1, 2, 3]
double_list(nums)
print(nums) # [2, 4, 6]
Dr. Taranum, Dept of AIML, KNSIT
42 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
Return new values
def squared_list(lst):
return [x*x for x in lst]
nums = [1, 2, 3]
print(squared_list(nums)) # [1, 4, 9]
4. Default List Parameters .ı (Important!)
Be careful when using lists as default parameters:
def add_item(x, items=[]):
[Link](x)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] (unexpected!)
–− Because the same list object is reused every time.
$ Correct way:
#
⬛
def add_item(x, items=None):
if items is None:
items = []
[Link](x)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [2] (works as expected)
5.3.14 List methods
The dot operator can also be used to access built-in methods of list objects.
Common List Methods
1. Adding Elements
append(x) → Add item to the end of the list.
nums = [1, 2, 3]
[Link](4)
Dr. Taranum, Dept of AIML, KNSIT
43 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
print(nums) # [1, 2, 3, 4]
insert(i, x) → Insert item at a specific position.
nums = [1, 2, 3]
[Link](1, 99)
print(nums) # [1, 99, 2, 3]
extend(iterable) → Add multiple items (from another list or iterable).
nums = [1, 2]
[Link]([3, 4, 5])
print(nums) # [1, 2, 3, 4, 5]
2. Removing Elements
remove(x) → Remove first occurrence of x.
nums = [1, 2, 3, 2]
[Link](2)
print(nums) # [1, 3, 2]
pop(i) → Remove and return item at index i.
Default: last element.
nums = [10, 20, 30]
print([Link]()) # 30
print(nums) # [10, 20]
clear() → Remove all items.
nums = [1, 2, 3]
[Link]()
print(nums) # []
3. Searching & Counting
index(x) → Find index of first occurrence of x.
nums = [1, 2, 3, 2]
print([Link](2)) # 1
count(x) → Count occurrences of x.
Dr. Taranum, Dept of AIML, KNSIT
44 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
nums = [1, 2, 2, 3]
print([Link](2)) # 2
4. Sorting & Reversing
sort() → Sort the list in place (default: ascending).
nums = [3, 1, 2]
[Link]()
print(nums) # [1, 2, 3]
With reverse:
[Link](reverse=True)
print(nums) # [3, 2, 1]
reverse() → Reverse order of elements.
nums = [1, 2, 3]
[Link]()
print(nums) # [3, 2, 1]
5. Copying
copy() → Shallow copy of the list.
a = [1, 2, 3]
b = [Link]()
[Link](4)
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3]
◆ Summary Table
Method Action
append(x) Add element at end
insert(i, x) Insert at position
extend(list) Add multiple elements
remove(x) Remove first match
pop(i) Remove & return item
Dr. Taranum, Dept of AIML, KNSIT
45 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
clear() Empty the list
index(x) Find position of item
count(x) Count occurrences
sort() Sort list
reverse() Reverse order
copy() Shallow copy
5.3.15 Pure functions and modifiers
Pure Functions
A pure function does not modify the original list (or object).
Instead, it computes something new and usually returns a new value.
Original input stays unchanged → no side effects.
Example (pure function):
def squared_list(lst):
new_list = []
for x in lst:
new_list.append(x * x)
return new_list
nums = [1, 2, 3]
result = squared_list(nums)
print(nums) # [1, 2, 3] (unchanged)
print(result) # [1, 4, 9]
–− squared_list is pure because it doesn’t change nums.
Modifiers
A modifier function changes (modifies) the original list directly.
Works in place → no new list is created.
Causes side effects.
Example (modifier):
def double_in_place(lst):
Dr. Taranum, Dept of AIML, KNSIT
46 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
for i in range(len(lst)):
lst[i] *= 2 # modifies directly
nums = [1, 2, 3]
double_in_place(nums)
print(nums) # [2, 4, 6] (changed)
–− double_in_place is a modifier because it updates nums itself.
Comparison
Feature Pure Function Modifier
Returns new list $
#
⬛ Yes + Usually not
Changes original + No $
#
⬛ Yes
Side effects + None $
#
⬛ Yes
Easier to reason $
#
⬛ Yes + No
$ In summary:
#
⬛
Pure functions → don’t change input, return new result.
Modifiers → directly change the object (like lists).
5.3.16 Functions that produce lists
These are functions (built-in or user-defined) that return a list as their result.
1. Built-in functions producing lists
Actually, many built-ins return iterators, so you need list(...) to turn them into lists.
list() constructor
s = "hello"
print(list(s)) # ['h', 'e', 'l', 'l', 'o']
range() with list()
nums = list(range(5))
print(nums) # [0, 1, 2, 3, 4]
map() with list()
nums = [1, 2, 3]
Dr. Taranum, Dept of AIML, KNSIT
47 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
squares = list(map(lambda x: x*x, nums))
print(squares) # [1, 4, 9]
filter() with list()
nums = [10, 15, 20, 25]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [10, 20]
2. User-defined functions producing lists
You can write your own functions that return lists.
Example: return all divisors of a number
def divisors(n):
return [i for i in range(1, n+1) if n % i == 0]
print(divisors(12)) # [1, 2, 3, 4, 6, 12]
Example: generate Fibonacci numbers
def fibonacci(n):
seq = [0, 1]
for i in range(2, n):
[Link](seq[-1] + seq[-2])
return seq[:n]
print(fibonacci(7)) # [0, 1, 1, 2, 3, 5, 8]
5.3.17 Strings and lists
Similarities between Strings and Lists
Ø Both are sequences → ordered collections of elements.
Ø Both support indexing and slicing.
Ø Both work with for loops.
Example:
s = "hello"
lst = [10, 20, 30]
print(s[1]) # 'e'
print(lst[1]) # 20
Dr. Taranum, Dept of AIML, KNSIT
48 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
print(s[:3]) # 'hel'
print(lst[:2]) # [10, 20]
for ch in s:
print(ch, end=" ") # h e l l o
2. Differences
Feature String List
Mutability Immutable (cannot change characters direct) Mutable(canchange elements)
Element type Always characters (strings of length 1) Can hold any type (int, str,etc.)
Modification Must create a new string Can modify in place
Example:
s = "hello"
# s[0] = "H" + Error (strings immutable)
lst = [1, 2, 3]
lst[0] = 99
print(lst) # [99, 2, 3]
3. Converting Between Strings and Lists
String → List of characters
s = "hello"
chars = list(s)
print(chars) # ['h', 'e', 'l', 'l', 'o']
List of chars → String
chars = ['h', 'e', 'l', 'l', 'o']
s = "".join(chars)
print(s) # 'hello'
Split string into list of words
s = "Python is fun"
words = [Link]()
print(words) # ['Python', 'is', 'fun']
Dr. Taranum, Dept of AIML, KNSIT
49 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
Join list of words into string
words = ['Python', 'is', 'fun']
s = " ".join(words)
print(s) # 'Python is fun'
5.3.18 list and range
range() generates a sequence of numbers.
It doesn’t create a list by default → instead, it creates a range object (an iterable).
Common forms:
range(stop) → numbers from 0 to stop-1
range(start, stop) → numbers from start to stop-1
range(start, stop, step) → numbers with increments of step
Examples:
print(range(5)) # range(0, 5) (not a list yet)
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 7))) # [2, 3, 4, 5, 6]
print(list(range(1, 10, 2))) # [1, 3, 5, 7, 9]
print(list(range(10, 0, -2))) # [10, 8, 6, 4, 2]
Using range with Lists and Loops
Iterating over a list by index
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i, fruits[i])
− Output:
–
0 apple
1 banana
2 cherry
Creating a list using range
numbers = list(range(1, 6))
Dr. Taranum, Dept of AIML, KNSIT
50 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
print(numbers) # [1, 2, 3, 4, 5]
Range vs List
Feature range list
Type Immutable sequence object Mutable sequence object
Memory use Lightweight (lazy generation) Stores all elements in memory
Conversion Use list(range(...)) Already a list
Example (big numbers):
r = range(1000000) # lightweight
print(len(r)) # 1000000
lst = list(r) # converts to actual list (uses a lot of memory!)
5.3.19 Nested lists
A nested list is simply a list where each element can also be a list.
Think of it like a matrix or table.
Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Here:
matrix[0] → [1, 2, 3]
matrix[1][2] → 6
Accessing Elements
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[0]) # [1, 2]
print(matrix[0][1]) # 2
print(matrix[2][0]) # 5
Looping Through Nested Lists
Dr. Taranum, Dept of AIML, KNSIT
51 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
Outer loop only (rows):
for row in matrix:
print(row)
Nested loops (rows + elements):
for row in matrix:
for val in row:
print(val, end=" ")
− Output:
–
123456
Modifying Nested Lists
You can change inner elements just like normal lists:
matrix = [[1, 2], [3, 4]]
matrix[0][1] = 99
print(matrix) # [[1, 99], [3, 4]]
Creating Nested Lists
Manual:
nested = [[0]*3, [0]*3, [0]*3]
print(nested) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
ı. Be careful with multiplication for nested lists:
wrong = [[0]*3]*3
wrong[0][0] = 1
print(wrong) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]] (all rows changed!)
$ Correct way:
#
⬛
matrix = [[0 for _ in range(3)] for _ in range(3)]
print(matrix) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
5.3.20 Matrices
A matrix is a 2D collection of numbers arranged in rows and columns.
In Python, there’s no built-in matrix type, but we can use nested lists.
Dr. Taranum, Dept of AIML, KNSIT
52 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
Example (3×3 matrix):
matrix = [
[1, 2, 3], # row 0
[4, 5, 6], # row 1
[7, 8, 9] # row 2
]
Accessing Elements
print(matrix[0]) # [1, 2, 3] → first row
print(matrix[1][2]) # 6 → row 1, column 2
print(matrix[2][0]) # 7 → row 2, column 0
Looping Through a Matrix
Loop over rows:
for row in matrix:
print(row)
Loop over each element:
for row in matrix:
for val in row:
print(val, end=" ")
− Output:
–
123456789
Common Matrix Operations
(a) Transpose of a Matrix
(Switch rows ↔ columns)
matrix = [[1, 2, 3], [4, 5, 6]]
transpose = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
print(transpose) # [[1, 4], [2, 5], [3, 6]]
Dr. Taranum, Dept of AIML, KNSIT
53 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 2
(b) Adding Two Matrices
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
result = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
print(result) # [[6, 8], [10, 12]]
(c) Multiplying Two Matrices
A = [[1, 2], [3, 4], [5, 6]]
B = [[7, 8, 9], [10, 11, 12]]
result = [[sum(A[i][k] * B[k][j] for k in range(len(B)))
for j in range(len(B[0]))]
for i in range(len(A))]
print(result)
# [[27, 30, 33],
# [61, 68, 75],
# [95, 106, 117]]
Dr. Taranum, Dept of AIML, KNSIT