0% found this document useful (0 votes)
2 views66 pages

Module-2 Py

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)
2 views66 pages

Module-2 Py

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

PYTHON PROGRAMMING

Module-2
Strings: 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, Looping and counting,
Optional parameters, The built-in find method, The split method, Cleaning up
your strings, The string format method.
Tuples: 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.

5.1 Strings

5.1.1 A Compound Data Type


A compound data type is a data type that consists of multiple smaller values
combined into a single structure.
Unlike simple data types (such as int, float, or bool), compound data types
contain multiple values.

Examples of Compound Data Types


 String (str) → Made up of characters
 List (list) → Made up of elements
 Tuple (tuple) → Made up of grouped values

1
PYTHON PROGRAMMING

5.1.2 Working with Strings as Single Things


In Python, a string is not just a collection of characters — it is an object.
Earlier, we learned that objects have:
 Attributes (properties)
 Methods (functions that belong to the object)
For example:
[Link](90)
Here, turn() is a method that belongs to the object tess.

Strings Are Also Objects


Just like a turtle object, a string object also has its own methods that can
perform operations on it.
Example:

Output:
HELLO, WORLD!

🔎 Explanation:
 "Hello, World!" is a string object.
 upper() is a method that converts all characters into uppercase.
 It creates a new string.
 The original string (our_string) remains unchanged.
This shows that strings are immutable in Python (they cannot be changed
directly).

2
PYTHON PROGRAMMING

🔹 Common String Methods


Some useful string methods include:

Example:

🔹 How to See Available Methods


Python provides many built-in string methods (around 70+ methods).
To see available methods in an editor like:
 Spyder
 PyScripter
 VS Code
 Jupyter Notebook

3
PYTHON PROGRAMMING

You can type:

After typing the dot (.), press Tab, and your editor will display a list of available
methods.

5.1.3 Working with the Parts of a String


In Python, a string is an ordered sequence of characters.
Each character in the string has a specific position number, called an index.
Python uses square brackets [ ] to access individual characters from a string.
This is known as indexing.

1. What is Indexing?
An index:
 Is a number written inside square brackets [ ]
 Specifies the position of an element in an ordered collection
 Can be any valid integer expression
In Python, we use square brackets [ ] to access a specific character from a
string.
This is called indexing.
Example:

Here both access index 2


Output :
a

4
PYTHON PROGRAMMING

Explanation
 "banana" is the string.
 fruit[1] means: select the character at index position 1.
 The result is 'a'.
In Python (and most programming languages), counting starts from zero, not
one.
This is known as zero-based indexing.
For the string "banana":
fruit[0] → 'b'
fruit[1] → 'a'
fruit[2] → 'n'

Note :
o Python does not have a separate character data type.
o A single character like 'a' is simply a string of length 1.

We can use enumerate to visualize the indices:


Example:

Output:

This shows:
 The first value → index
 The second value → character at that index

5
PYTHON PROGRAMMING

Indexing Works for Lists Also


The same [ ] works for lists.
Example :

Output:
11

Output:
Angelina

5.1.4 Length
The len() function in Python is a built-in function used to find the length of a
string.
When applied to a string, it returns the number of characters present in that
string.
The len() function counts:
 Letters
 Spaces
 Special characters
 Numbers
Everything inside the string is counted as a character.

🔹 Syntax:
len(string_name)

6
PYTHON PROGRAMMING

🔹 Example:

🔹 Output:
6

Finding the Last Character

This will gives an error message saying : IndexError: string index out of range
Because, here we are trying to access word[6] last element in the word banana
has index value 5.
So, index out of bound exception.

Correct Way to Get the Last Character


Since indexing starts at 0, the last character index is:
length – 1
Correct Example:

Output:
6

7
PYTHON PROGRAMMING

Python provides a simpler way to access characters from the end using
negative indexing.

🔹 Rules of Negative Indexing:

Example 1: Last Character

Output:
a

Output:
n

Negative Indexing Works for Lists Also


The same concept applies to lists.
Example:

8
PYTHON PROGRAMMING

📌 Conclusion
The len() function is used to calculate the length of a string. Since Python uses
zero-based indexing, the last character is always at position length - 1. Negative
indexing provides a simple and efficient way to access characters from the end
of a string.

5.1.5 Traversal and the for Loop


When we process a string one character at a time from beginning to end, it is
called Traversal.
Example:
 Take first character
 Do something
 Go to next character
 Continue until end
One way to perform a traversal is by using a while loop. In this approach, an
index variable is initialized to zero and used to access each character of the
string using its position. The loop continues as long as the index is less than the
length of the string. When the index becomes equal to the length of the string,
the condition becomes false and the loop stops. Since indexing starts at zero,
the last valid index of a string is len(string) - 1.

⚠ Why is this not good?


 Code is longer
 Uses manual indexing
 Less readable
 More chance of mistakes

9
PYTHON PROGRAMMING

Although this method works, it requires explicit handling of the index variable
and the loop condition. As a result, the code becomes longer and less clear.
A more convenient and expressive way to traverse a string is by using a for
loop. The for loop automatically iterates over each character in the string
without the need for an index variable. During each iteration, the next
character in the string is assigned to a loop variable. The loop continues until all
characters have been processed. This makes the for loop simpler, shorter, and
easier to understand compared to the while loop.

Traversal using a for loop demonstrates the power and readability of Python’s
design when working with sequences such as strings.

The for loop can be used together with string concatenation (joining strings
using +) to create new words or strings.
For example, if we have several beginning letters (prefixes) and one common
ending (suffix), we can join each beginning letter with the same ending to
produce a list of new words. This shows how the for loop moves through each
element one by one and combines it with another string to generate structured
output.
When the produced words are arranged in alphabetical order, the series is
called an abecedarian series. This means the elements appear in alphabetical
order.

10
PYTHON PROGRAMMING

Output:

In simple terms, traversal means visiting each element in a sequence one by


one. The for loop is an easy and clear way to do this when working with strings.

5.1.6 Slices
A substring of a string can be obtained by using a slice. Slicing allows us to
extract a part of a string. In the same way, slicing can also be used with lists to
extract a sublist.
The slicing operator uses the notation [n:m]. This returns the part of the string
starting from the n’th index up to the m’th index, including the character at
position n but excluding the character at position m.

Example with List:

Output:

11
PYTHON PROGRAMMING

If we think of indices as positions between characters, the slice [n:m] copies


the portion between positions n and m. When both n and m are within the
valid range, the length of the slice will be (m - n).
There are three important special cases in slicing:
1. If the first index is omitted (before the colon), the slice starts from the
beginning of the string or list.
2. If the second index is omitted (after the colon), the slice goes up to the
end of the string or list.
3. If the ending index is greater than the length of the string or list, Python
does not produce an error. Instead, it returns all elements up to the end.
For example:
 word[:3] means from the beginning up to index 3 (excluding 3).
 word[3:] means from index 3 to the end.
 word[3:999] also means from index 3 to the end, even though 999 is
outside the range.

When the entire slice is written as phrase[:], it means the whole string is
copied.
Similarly, friends[4:] means all elements from index 4 to the end of the list.
Negative indices can also be used in slicing. For example, phrase[-5:-3] means
slicing from the fifth character from the end up to the third character from the
end, excluding the last position mentioned.
Thus, slicing is a powerful way to extract parts of strings or lists without
modifying the original data.

12
PYTHON PROGRAMMING

5.1.7 String Comparison


In Python, comparison operators can also be used with strings. These
operators allow us to compare two strings to check whether they are equal or
to determine their order.
To check whether two strings are equal, the equality operator == is used. If
both strings contain exactly the same sequence of characters, the condition
becomes true.

Output:

String comparison is also useful for arranging words in lexicographical order


(dictionary order). Python compares strings character by character, starting
from the first character. The comparison continues until a difference is found.
The result depends on the Unicode (ASCII) value of the differing characters.
The relational operators <, >, <=, and >= can be used to determine whether one
word comes before or after another word alphabetically.
Example: Python compares strings in alphabetical order(Lexicographical Order
or Dictionary order).

Output:
Your word comes before banana.

13
PYTHON PROGRAMMING

In Python, all uppercase letters come before all lowercase letters. This
happens because uppercase and lowercase letters have different Unicode
values. Therefore, a word beginning with a capital letter may appear before a
lowercase word, even if dictionary rules suggest otherwise.
For example, the word "Zebra" comes before "banana" in Python’s comparison
because uppercase "Z" has a lower Unicode value than lowercase "b".

Output:
Your word comes before banana.

To avoid this issue, a common solution is to convert both strings into a standard
format before comparing them. Usually, programmers convert both strings to
either all lowercase or all uppercase using methods like lower() or upper(). This
ensures fair and consistent comparison.

Now:
 "zebra" is compared with "banana"
 Correct alphabetical comparison happens

Another limitation of simple string comparison is that Python only compares


characters, not meanings.
For example, it cannot understand that "zebras" are animals and not fruits. It
simply compares text based on character values.

14
PYTHON PROGRAMMING

Thus, string comparison in Python works based on character order, not


meaning, and careful formatting is often required to get expected alphabetical
results.

5.1.8 Strings are Immutable


In Python, strings are immutable.
Immutable means that once a string is created, it cannot be changed.
A common mistake is trying to change a character in a string using the indexing
operator [] on the left side of an assignment. For example, attempting to
replace the first character of a string will result in an error. Python does not
allow modification of individual characters inside an existing string.
When such an operation is attempted, Python produces a runtime error:
TypeError: 'str' object does not support item assignment

Instead of producing the output Jello, world!, this code produces the runtime
error TypeError: 'str' object does not support item assignment.
This error occurs because strings do not support changing their contents after
creation.
Since strings cannot be modified, the correct approach is to create a new string
instead of changing the original one. This can be done by combining
(concatenating) new characters with parts (slices) of the original string.
For example, if we want to change the first letter of "Hello, world!" to "J", we
create a new string by:
 Adding the new first character
 Combining it with the rest of the original string using slicing

15
PYTHON PROGRAMMING

This process does not modify the original string. Instead, it creates a
completely new string with the desired change.
Thus, string immutability means:
 Individual characters cannot be reassigned.
 Any modification results in the creation of a new string.
 The original string remains unchanged.
This property makes strings safer and more predictable when used in
programs.

5.1.9 The in and not in Operators


The in operator is used to check the membership.
When both operands are strings, in checks whether the left string is a substring
of the right string.
If the left string is found inside the right string, the result is True.
If it is not found, the result is False.
For example:
 "p" in "apple" is True because the character "p" exists in "apple".
 "i" in "apple" is False because "i" does not exist in "apple".
 "ap" in "apple" is True because "ap" is a substring of "apple".
 "pa" in "apple" is False because "pa" does not appear in that order.
A string is always considered a substring of itself.
The empty string ("") is also considered a substring of any string. Therefore:
 "apple" in "apple" is True.
 "" in "apple" is True.
These special situations are called edge cases, and they are important in
computer science.

16
PYTHON PROGRAMMING

The not in operator works in the opposite way of in.


It returns True if the left string is not found in the right string, and False if it is
found.
For example:
 "x" not in "apple" is True because "x" is not present in "apple".
The in and not in operators can be combined with loops and string
concatenation to process strings.
For instance, they can be used to remove certain characters from a string. A
common example is removing vowels from a phrase.
In such a function:
 A string containing all vowels ("aeiou") is defined.
 Each letter of the input phrase is checked.
 If the lowercase version of the letter is not in the vowels string, it is
added to a new string.
 The result is a string without vowels.
The use of [Link]() ensures that both uppercase and lowercase vowels are
handled correctly. Without converting to lowercase, uppercase vowels would
not be detected and removed.
Thus, the in and not in operators provide a simple and powerful way to check
substring membership and are widely used in string processing tasks.

Important to note is the [Link]() in line 5, without it, any uppercase


vowels would not be removed.
17
PYTHON PROGRAMMING

5.1.10 A find Function


The function my_find(haystack, needle) is designed to search for a character
inside a string.
In this function:
 The parameter haystack represents the main string in which the search
is performed.
 The parameter needle represents the character that we want to find.

The function examines each character in the string one by one using a loop. It
uses enumerate() to access both:
 The index of each character
 The character itself
During traversal:
 If the current character is equal to the needle, the function immediately
returns the index where it was found.
 If the loop finishes without finding the character, the function returns -1.
Returning -1 indicates that the character does not exist in the string.
This behavior is similar to Python’s built-in find() method. The built-in find()
method:
 Returns the index of the first occurrence of the given character (or
substring).

18
PYTHON PROGRAMMING

 Returns -1 if the character is not found.


In a conceptual sense, the find() function is the opposite of indexing:
 Indexing takes an index and returns the character at that position.
 find() takes a character and returns the index where it appears.

Compare with Python’s Built-in find()

Output:
1
1
An important concept demonstrated in this function is the use of a return
statement inside a loop. As soon as the required character is found, the
function immediately exits without checking the remaining characters. This
avoids unnecessary computation.
This pattern is called a eureka traversal or short-circuit evaluation. The term
means that once the desired result is found, the process stops immediately
instead of continuing further. It improves efficiency because the program does
not waste time checking the rest of the string after finding the match.
Thus, the my_find function performs a search operation by traversing the string
and returning the position of the first occurrence of a specified character, or -1
if it does not occur.

19
PYTHON PROGRAMMING

5.1.11 Looping and Counting


This program demonstrates the looping and counting concept in Python using
the counter pattern.

This function:
 Counts how many times the letter "a" appears
 Returns that number
Output:
True

🔹 What is Looping?
Looping means repeating a block of code multiple times.
In this program, a for loop is used to go through each character (letter) in a
string.

🔹 What is Counting (Counter Pattern)?


The counter pattern is a common programming technique used to count how
many times something happens.
It involves:
1. Initializing a counter variable (usually set to 0).
2. Updating (incrementing) the counter whenever a condition is true.
3. Returning the final count.

20
PYTHON PROGRAMMING

5.1.12 Optional Parameters


An optional parameter is a parameter that has a default value.
If the user does not provide a value while calling the function, Python
automatically uses the default value.
Example:

Output:
1
1
In the improved function definition:
 The parameter start=0 means that if no starting position is given, the
search automatically begins at index 0.
 If a third argument is provided, it replaces the default value.

5.1.13 The Built-in find() Method


The find() method is a built-in string method in Python that is used to search
for a substring inside a string.
It returns the index of the first occurrence of the substring. If the substring is
not found, it returns -1.
Syntax
[Link](substring, start, end)

21
PYTHON PROGRAMMING

Parameters:
 substring → the text to search
 start (optional) → starting index
 end (optional) → ending index

The built-in find() method:


 Searches for a character or substring within a string.
 Returns the index of the first occurrence.
 Returns -1 if the substring is not found.

5.1.14 The split() Method


The split() method is a built-in string method in Python. It is used to divide a
string into smaller parts and store them in a list.
The result of the split() method is always a list. Each word from the original
string becomes an element in that list.
Syntax
[Link](separator)
 separator is optional.
 If no separator is given, it splits based on whitespace.

🔹 What Does split() Do?


 It breaks a string into a list of words.
 By default, it splits the string wherever there is whitespace.
 Whitespace includes:
o Spaces

22
PYTHON PROGRAMMING

o Tabs
o Newlines
So, it removes the spaces and returns only the words.
Example 1:

Output:

Here:
 The original string contains spaces between words.
 split() separates each word.
 The result is a list of individual words.

Example 2: Example with Separator

Output:

Here:
 The string is split wherever there is a comma ,

23
PYTHON PROGRAMMING

5.1.15 Cleaning Up Your Strings


When working with strings, sometimes the data contains extra spaces or
unwanted characters.
Cleaning up strings means removing unnecessary whitespace or symbols to
make the data neat and usable.

🔹 Why Do We Clean Strings?


When users enter input, they may accidentally add:
 Extra spaces at the beginning
 Extra spaces at the end
 Tabs or newline characters
Example:
name = " Alice "
This string contains unwanted spaces.
To properly compare or process the string, we need to clean it.
Since strings in Python are immutable, we cannot directly modify the original
string. Instead, we must traverse the original string character by character and
construct a new string that excludes the unwanted characters.

Method 1: Manually Removing Punctuation

24
PYTHON PROGRAMMING

Better Method: Using string Module


Manually defining all punctuation symbols can be tedious and error-prone. To
simplify this task, Python provides a built-in module called string, which
contains a predefined constant named [Link].
This constant includes all standard punctuation characters, making the process
easier and more reliable.

[Link] already contains all punctuation symbols


After removing punctuation, the cleaned string can be combined with the
split() method. The split() method removes whitespace such as spaces, tabs,
and newline characters, and converts the cleaned string into a list of words.
By combining:
 A function to remove punctuation, and
 The split() method to separate words,
we obtain a powerful method for text processing. This is especially useful when
analyzing large text passages, counting word frequencies, or performing other
text-based operations.
Thus, cleaning up strings is an important step in preparing text data for
accurate and efficient processing.

25
PYTHON PROGRAMMING

5.1.16 The String format() Method


The string format() method is one of the most powerful and flexible ways to
create formatted strings in Python 3.
It allows values (variables, expressions, or constants) to be inserted into a
template string at specific positions called placeholders.
A template string contains placeholders written using curly braces:
{}
{0}
{1}
{name}
The format() method replaces these placeholders with given arguments.
Example

Output:

Here {0} refers to the first argument passed to format().

Index-based Placeholders
The numbers inside { } represent indexes of arguments.

Output:

26
PYTHON PROGRAMMING

{1} → second argument


{0} → first argument

Format Specification
Format specification is used inside {} in the format() method to control how
values appear in a string.
It starts with a colon : inside the placeholder.
Syntax
“ {index:format_spec}".format(value)

format_spec decides
✔ alignment
✔ width
✔ decimal precision
✔ type conversion

1. Alignment :
Controls where the value appears in the field.

Syntax
“{index : alignment width}".format(value)

27
PYTHON PROGRAMMING

Example:

Output:

2. Field Width
Field width specifies the minimum space reserved for a value inside a
formatted string.
Syntax
“{index : width}".format(value)
Example

Output:

Width = 10 → text length = 6 → 4 spaces added

Value Larger than Width

28
PYTHON PROGRAMMING

✅ Output
|||Programming|||
Value is NOT truncated

Note :
If the value is shorter → extra spaces are added
If the value is longer → full value is printed (not cut)

Field Width with Alignment

Output:

3. Type Conversion
Type conversion specifies how a value should be displayed inside a formatted
string.
It is written after : inside {}
Syntax
"{index:conversion}".format(value)

29
PYTHON PROGRAMMING

Common Type Conversion Codes

Example

4. Decimal Precision
Decimal precision controls how many digits appear after the decimal point
when displaying floating-point numbers.
Written using .numberf

30
PYTHON PROGRAMMING

Syntax:
"{index:.nf}".format(value)
n = number of decimal places

Example:

Output:

Value is rounded automatically

Example:

Output:

Format specification is a feature of the format() method that allows control


over alignment, width, precision, and type conversion of values using : inside
placeholders.

31
PYTHON PROGRAMMING

5.2 Tuples

5.2.1 Tuples are Used for Grouping Data


A tuple is a data structure used to group multiple values into a single
compound value.
It is written as a comma-separated sequence of values, usually enclosed in
parentheses.
Tuples are useful for storing related information like:
✅ Student record
✅ Employee details
✅ Movie details
Similar to structs or records in other languages.
Syntax:
tuple_name = (value1, value2, value3, ...)
Tuples are comma-separated values, parentheses are optional but
recommended.

Example
year_born = ("Paris Hilton", 1981)
Groups name and birth year together.

Tuple with Multiple Elements


julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")
Tuples can store different data types.

Tuple Indexing
Tuples support sequence operations similar to strings.
The index operator can access elements.

32
PYTHON PROGRAMMING

Example: julia[2]
Output
1967
An empty tuple is created as:
empty_tuple = ()

Tuples are an important Python data structure used for grouping related values
into a single object.
They behave like sequences but are immutable, ensuring data integrity and
efficient storage.

5.2.2 Tuple Assignment


Tuple assignment is a powerful feature in Python that allows multiple
variables to be assigned values simultaneously using tuples.
In this process, a tuple of variables on the left side of an assignment receives
values from a tuple on the right side.
Syntax
(variable1, variable2, ...) = (value1, value2, ...)
Each variable receives the corresponding value.

Important Rule

✅ Number of variables on left = number of values in tuple


❌ Otherwise → error

Tuple Packing
Packing means grouping multiple values into a tuple.
Example: bob = ("Bob", 19, "CS")
Here, values are packed into a single tuple.

33
PYTHON PROGRAMMING

Tuple Unpacking
Unpacking means extracting values from a tuple into variables.
Example:

After unpacking : Values from tuple are assigned to variables.

Swapping Variables Using Tuple Assignment:


Tuple assignment provides a simple way to swap values without using a
temporary variable.
Traditional Method
temp = a
a=b
b = temp
Tuple Assignment Method
(a, b) = (b, a)
Python evaluates the right side first and then assigns values to the left side
variables.

Tuple assignment is a flexible and efficient feature in Python that enables


simultaneous assignment of multiple values, simplifies variable swapping, and
supports tuple packing and unpacking, making programs more concise and
readable.

34
PYTHON PROGRAMMING

5.2.3 Tuples as Return Values


In Python, a function can return only one value.
However, by returning a tuple, multiple values can be grouped together and
returned as a single object.
Thus, tuples allow functions to return multiple results simultaneously.

This feature is helpful when a function needs to return related values, such as:

✅ highest and lowest score


✅ mean and standard deviation
✅ date components (year, month, day)
✅ ecological model results (number of rabbits and wolves)
✅ mathematical results (area and circumference)

Example: Circle Statistics Function

Output:

35
Python Programming

5.3 Lists
o A list is an ordered collection of values in Python.
o The values inside a list are called elements or items.
o Lists can store different data types (numbers, strings, objects, etc.)
o Lists are written using square brackets [ ] with elements separated by
commas.
o Lists are sequences, meaning the order of elements is maintained.
o Each element in a list can be accessed using indexing (starting from 0).
o Lists are mutable, so their elements can be changed after creation.
o Lists are similar to strings, but strings store only characters while lists
store any type of data.
Example
[1] Numbers = [10, 20, 30, 40] → list of integers
[2] Values = ["spam", "bungee", "swallow"] → list of strings
[3] Mixed = ["hello", 2.0, 5, [10, 20]] → mixed and nested list
[4] mixed = [10, "Alice", 3.14, True] → List of different data type

5.3.1 List Values


o A list value represents the actual elements stored in a list.
o A list value is created by enclosing elements inside square brackets [ ].
o Elements in a list are separated by commas.
o Lists can contain elements of the same or different data types.
Example:
numbers = [10, 20, 30, 40]
words = ["spam", "bungee", "swallow"]
A list can contain another list, which is called a nested list.
Example:

Here,
[10, 20] is another list with two elements.
Python Programming

A list with no elements is called an empty list, written as [].


Example:
an_empty_list = []

Lists can be assigned to variables and passed as arguments to functions.


Example:

Output:

5.3.2 Accessing Elements


Elements of a list can be accessed using the index operator [ ], similar to
accessing characters in a string.
The value inside brackets specifies the index position of the element.
Example:

Output:
Python Programming

Any integer expression can be used as an index.

Output:
30

Using a non-integer index (like float) produces a TypeError.


o List indices must be integers.
Example: numbers[1.0]
TypeError: list indices must be integers, not float

Accessing an index that does not exist results in IndexError (list index out of
range).

Output:

Accessing elements one by one using a loop is called list traversal. A more
readable way of traversal is to iterate directly over elements instead of indices.
Python Programming

5.3.3 List Length


o The len() function returns the number of elements in a list.
o List length is equal to the total count of items in the list.
Example

Output:
4

o Using len() in Loops


When accessing list elements using indexing, it is recommended to use len() as
the upper bound instead of a constant value.
This ensures that the loop works correctly even if the list size changes.

Output:

o In index traversal, the last valid index is len(list) - 1.


Python Programming

Output:

o A list containing another list counts the nested list as one element.

Output:

o Direct iteration over list elements is generally more readable than using
indices.
Index-based traversal

Direct traversal (Better)

Direct iteration (for num in numbers) is generally preferred over index-based


traversal because it improves readability, reduces errors, and provides a
simpler and more Pythonic way to traverse list elements compared to index-
based loops.
Python Programming

5.3.4 List Membership


o in and not in are Boolean operators used to test membership in a list or
sequence.
o The operator in returns True if an element exists in the list.
o The operator not in returns True if an element does not exist in the list.
o Membership testing works with lists, strings, tuples, and other sequences.
o It helps write clean and readable conditions without complex loops.
o Membership can be used inside loops to check whether a value exists in
nested lists.
o Useful for tasks like counting occurrences, searching elements, and filtering
data.
Example:

Output:
Python Programming

Membership operators can also be used in nested structures like lists inside
tuples.
Example — counting students taking Computer Science:

Output:

5.3.5 List Operations


Python supports several operators for performing operations on lists.
Two important operators are:
+ → Concatenation
* → Repetition
Concatenation creates a new list containing elements of both lists.
Python Programming

Output:

The * operator is used for list repetition, repeating elements multiple times.
Repetition produces a new list with elements repeated according to the given
number.

Output:

This operation duplicates the list elements repeatedly.

List operations such as concatenation and repetition provide simple ways to


combine and duplicate list elements. List operations do not modify original lists
unless reassigned. These operations help in combining data and generating
repeated patterns.

5.3.6 List Slices


o List slicing is used to extract a sublist (portion of a list) from an existing
list.
o The slicing syntax is similar to string slicing: list[start : end].
o The start index is included, while the end index is excluded.
o If the start index is omitted, slicing begins from the first element.
o If the end index is omitted, slicing continues to the last element.
o Using [:] creates a copy of the entire list.
o List slicing works similarly to string slicing.
Examples
 a_list[:] → ['a', 'b', 'c', 'd', 'e', 'f']
 a_list[:4] → ['a', 'b', 'c', 'd']
Python Programming

Example:

Output:

5.3.7 Lists are Mutable


Unlike strings, lists are mutable, meaning their elements can be changed after
creation.
This allows modification, insertion, and deletion of list elements without
creating a new list.
Using the index operator on the left side of assignment, we can modify a
specific element.
Changing an element using indexing is called item assignment.
Example:

Output:
['pear', 'apple', 'orange']
This process is called item assignment.
Python Programming

Slice assignment allows modification of multiple elements simultaneously.


Example:

Output:

Assigning an empty list to a slice removes elements from a list.


Example:

Output:

Inserting values into an empty slice position adds new elements at a desired
location (Elements can be inserted into an empty slice).
Python Programming

5.3.8 List Deletion


o Python provides the del statement to remove elements from a list.
o del deletes an element using its index position.
o If the index does not exist, Python raises an IndexError.
o The del statement can also be used with slicing to remove multiple
elements at once.
o When deleting with slices, elements are removed from the start index
up to (but not including) the end index.
o del improves readability compared to deleting elements using slice
assignment.

Example

Output

If the specified index does not exist, Python raises an error.


Example:
del a[5]
Output:
IndexError: list assignment index out of range

The del statement can also remove a sublist using slicing.


Python Programming

5.3.9 Objects and References


 In Python, variables store references to objects, not the actual data
itself.
 When two variables are assigned the same value, they may refer to the
same object or different objects.
There are two possible ways the Python interpreter could arrange its memory:

 The is operator checks whether two variables refer to the same object in
memory.
 The == operator checks whether two variables have the same value.
 For immutable objects (like strings), Python may optimize memory by
making variables refer to the same object.
 For mutable objects (like lists), variables with identical values usually
refer to different objects.
 Therefore, lists can have equal values but different memory references.
Examples
Python Programming

Output:

5.3.10 Aliasing
 Aliasing occurs when two or more variables refer to the same object in
memory.
 Assigning one variable to another creates an alias.
 The is operator can be used to check aliasing (same object reference).
 When a mutable object (like a list) is aliased, changes made through one
variable affect the other.
 Aliasing can be useful but may lead to unexpected side effects when
modifying mutable objects.
 It is generally safer to avoid aliasing with mutable objects such as lists.
 Aliasing does not cause problems with immutable objects (strings,
tuples) because they cannot be modified.
Example:

Output:
True
This shows that a and b refer to the same list object.
Python Programming

Effect of Aliasing
Since both variables refer to the same object, changes made using one variable
affect the other.

Output:

Modification using b also changes a.

5.3.11 Cloning Lists


Cloning means creating a new list with the same elements as the original list,
so that changes to one list do not affect the other.
It avoids the problem of aliasing (two variables referring to the same list).
Why cloning is needed
 When we assign one list to another using b = a, both variables refer to
the same list.
 Any modification through one variable affects the other.
 To keep the original list unchanged, cloning is required.
Method to clone a list
 The simplest way is using the slice operator:
Example: b = a[:]
Key concept
 a[:] returns a new list containing all elements of a(Taking a slice always
creates a new list object.) The new list has a different memory location
Python Programming

Example:

 After cloning, both lists have same values but different memory locations.
 Changes in the cloned list do not affect the original list.
 Cloning helps preserve the original data while performing modifications.

5.3.12 Lists and for Loops


A for loop is used to traverse (iterate through) each element of a list one by
one.
General syntax

The loop variable takes each value from the list sequentially.
Example: Iterating through a list

Output:

Each element of the list is assigned to the loop variable one by one.
Python Programming

Using list expressions


Any list expression can be used inside a for loop:

Output:

Here,
range(20) generates numbers from 0 to 19
Condition number % 3 == 0 selects multiples of 3
So the loop prints multiples of 3 within 0–19

Modifying list elements using for loop


 Since lists are mutable, we can change elements while traversing.
 Use index-based traversal:

Output:

range(len(xs)) gives indexes of the list.


Python Programming

Using enumerate() (Better approach)


 enumerate() returns pairs of (index, value).

More readable and Pythonic than index-based loops.


Example

Output includes both index and element:

5.3.13 List Parameters


Passing lists to functions
 When a list is passed as an argument to a function, a reference to the list
is passed, not a copy.
 Both the caller variable and the function parameter refer to the same list
object.
Aliasing in list parameters
 Parameter passing creates an alias(The parameter inside the function
becomes an alias of the original list variable).
 The function parameter and original variable point to the same memory
location.
 Therefore, changes made inside the function affect the original list.
Python Programming

Example:

Output:
[4, 10, 18]

 Lists are mutable objects, so changes affect the shared object.


 Stuff_list and things reference the same list.
 stuff_list becomes an alias of things.
 The function modifies elements directly in the shared list.

State Snapshot Idea

 When a list is passed as an argument to a function, the caller variable


and the function parameter refer to the same list object in memory.
 No new list is created; only another reference (name) to the existing
object is passed.
 This situation is called aliasing, where multiple variables point to the
same object.
 Any modification made through the function parameter affects the
original list in the caller.
 The state snapshot (memory diagram) would show two variable names
pointing to one list object.
 This explains why in-place changes inside the function are visible after
the function call.
Python Programming

5.3.14 List Methods


 List methods are built-in functions used to perform operations on lists.
 They are accessed using the dot operator (.).
Important List Methods
1. append(element)
 Adds a single element to the end of the list.
 Example: [Link](5)
2. insert(index, element)
 Inserts an element at a specified index.
 Shifts remaining elements to the right.
 Example: [Link](1, 12)
3. count(element)
 Returns the number of times an element appears in the list.
 Example: [Link](12)
4. extend(list)
 Adds all elements of another list to the end of the list.
 Example: [Link]([5, 9, 5, 11])
5. index(element)
 Returns the index of the first occurrence of an element.
 Example: [Link](9)
6. reverse()
 Reverses the order of elements in the list.
 Example: [Link]()
7. sort()
 Sorts the list in ascending order permanently.
 Example: [Link]()
Python Programming

8. remove(element)
 Removes the first occurrence of the element from the list.
 Example: [Link](12)

Example:
Python Programming

5.3.15 Pure Functions and Modifiers


1. Modifier Functions
 Functions that change the original list passed as an argument.
 These changes are called side effects.
 The function directly modifies the shared list object.
Key idea
 Original data is changed.
 No new list is created.
 Parameter and argument become aliases.
Example (Modifier)

Output:
[4, 10, 18]
Here, the original list is modified.

2. Pure Functions
 A pure function does not modify the original list.
 It creates and returns a new list.
 Communication happens only through parameters and return value.
Key idea
 No side effects.
Python Programming

 Original list remains unchanged.


 Safer and easier to debug.
Example (Pure function)

Output:
[2, 5, 9]
[4, 10, 18]
The original list remains unchanged.

Since pure functions return a new list, we can safely do:


Example:

Output
[4, 10, 18]
Python Programming

5.3.16 Functions that Produce Lists


 Some functions are designed to create and return a list.
 These functions usually follow a pure function approach (no
modification of arguments).
 They build a new list step by step and return it.

✅ Standard Pattern for Creating Lists in Functions


Step-1: Initialize an empty list
Step-2: Loop through required values
Step-3: Create a new element
Step-4: Append the element to the list
Step-5: Return the final list
This pattern is widely used in Python programming.

Example: Prime Numbers Less Than n


Assume is_prime(x) checks whether a number is prime.

5.3.17 Strings and Lists


 Python provides methods to convert between strings and lists.
 The two important methods are:

o split() → string ➝ list


Python Programming

o join() → list ➝ string

1. split() Method
 Splits a string into a list of substrings (words).
 By default, whitespace is used as the separator.
Example

Output:

split() with delimiter


 A delimiter specifies the boundary for splitting.
 The delimiter itself does not appear in the result.
Example
[Link]("ai")
Output
['The r', 'n in Sp', 'n...']

2. join() Method
 The inverse of split().
 Combines list elements into a single string.
 A separator (glue) is placed between elements.
Python Programming

Example

Output

join() variations
Multi-character glue
o Multi-character glue is a separator string containing two or more
characters that is used to join elements of a sequence (usually a list of
strings) into a single string.

Output

Empty glue
o Empty glue means using an empty string ("") as the separator when
joining elements.
o This joins all elements without any separator between them.

Output
Python Programming

Key Points
 split() converts string → list.
 join() converts list → string.
 split() removes the delimiter from the result.
 join() does not modify the original list.
 The separator in join() can be empty, single, or multi-character.
 These methods are useful in text processing and data cleaning.

5.3.18 List and range


1. list() Function
 list() is a type conversion function that converts an iterable object into a
list.
 It can convert strings, tuples, range objects, etc., into lists.
Example (string → list)

Output:

Rejoining

Output
Python Programming

2. range Object
 range() generates a sequence of numbers but does not immediately
create a list of values.
It is lazy meaning
 range produces values only when needed
 Acts like a promise to generate numbers on demand
 Saves memory and improves efficiency
Example demonstrating laziness

Function stops once condition is met


range does not generate all values up to n

Converting range to list


 Wrapping range inside list() forces Python to create all elements.
 list(range(n)) forces range to produce all elements.
Example

Output
Python Programming

5.3.19 Looping and Lists


 Loops allow computers to repeat computations quickly and accurately.
 Lists are often used with loops to store data for later use.
 However, creating unnecessary lists can waste memory and time.
Avoid unnecessary lists
 Lists should be created only when data must be stored for later use
 If storage is not required, avoid building lists to save memory and time
Example:
Function 1 — Using a list

Steps:
 Generates random numbers
 Stores all numbers in a list
 Calculates the sum later
Disadvantages
 High memory usage
 Slower performance
 May cause memory overflow
Python Programming

Function 2 — Without list

Steps:
 Generates numbers
 Adds immediately to total
 No list created
Advantages
 Less memory usage
 Faster execution
 No risk of memory error

5.3.20 Nested Lists


 A nested list is a list that contains another list as one of its elements.
 It allows storing multi-level or hierarchical data.
Example
nested = ["hello", 2.0, 5, [10, 20]]
Here, [10, 20] is a nested list at index 3.
Python Programming

Accessing Nested List

Output:

5.3.21 Matrices
A matrix is a two-dimensional data structure consisting of rows and columns.
In Python, matrices are commonly represented using nested lists.
Matrix representation

Here:
 mx is a list containing three rows
 Each row itself is a list
Python Programming

Accessing matrix elements

Output:

You might also like