Mod 2 Notes Python
Mod 2 Notes Python
Module 2
Chapter 1- Strings
Introduction:
Strings are sequences of one or more characters, used for handling textual data.
In Python, a string is a basic data type used to represent sequences of characters, including alphabets,
numbers, special symbols, white space, etc.
Strings are created by enclosing characters within single quotes ('...'), double quotes ("..."), or triple
quotes ("""...""" or '''...'''). Triple quotes.
Example:
single_quoted = 'Hello'
double_quoted = "World"
multi_line = """This is a multi-line string."""
The upper() method in Python is a built-in string method used to convert all lowercase letters within a
string to their uppercase.
Example 1:
x = "Hello Python"
# Positive indexing (index range from 0 to n-1)
print(x[0]) # Output: H
print(x[6]) # Output: P
# Negative indexing (index range from -1 to -n)
print(x[-1]) # Output: n
print(x[-7]) # Output: P
We can use enumerate to visualise the indices. Enumerate() is a built-in function in Python that allows
you to keep track of the number of iterations in a loop. Example
Program:
x = "Python"
for index, char in enumerate(x):
print(f"Index: {index}, Character: {char}")
Output:
Index: 0, Character: P
Index: 1, Character: y
Index: 2, Character: t
Index: 3, Character: h
Index: 4, Character: o
Index: 5, Character: n
Example 2:
>>> fruit = "Banana"
>>> list(enumerate(fruit))
[(0, 'B'), (1, 'a'), (2, 'n'), (3, 'a'), (4, 'n'), (5, 'a')]
Example 3:
>>> 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'
Length
In Python, the built-in len() function is used to determine the length of a string.
This function returns the number of characters in the string, including spaces and special characters.
Example:
>>> word = "banana"
>>> len(word)
6
In Python, String index out of range (IndexError) occurs when we try to access an index that is out of
the range of a string, or we can say the length of the string.
A lot of computations involve processing a string one character at a time. Often, they start at the
beginning, select each character in turn, perform an operation on it, and continue until the end. This
pattern of processing is called a traversal.
This is the most common and Pythonic way to use a for loop for traversal. The loop directly assigns each
item from the iterable to the loop variable in successive iterations. Example
Program Output
my_string = "Python" P
for char in my_string: y
print(char) t
h
o
n
The following example shows how to use concatenation and a for loop to generate an abecedarian
series. Abecedarian refers to a series or list in which the elements appear in alphabetical order.
Program Output
Slices
String slicing in Python is a way to get specific parts of a string by using start, end and step values. It's
beneficial for text manipulation and data parsing.
It is a method for extracting a portion, or substring, from a larger string.
The slice operator in Python, denoted by square brackets [:] with colons.
The basic syntax for slicing is [start:stop: step]
start: The index where the slice begins (inclusive). If omitted, it defaults to the beginning of the sequence
(index 0), ex. [:3]
stop: The index where the slice ends (exclusive). The element at this index is not included. If omitted, it
defaults to the end of the sequence. ex. [5:]
step: The increment between elements in the slice. If omitted, it defaults to 1. A negative step reverses
the order of the slice.
Example:
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
my_string = "Hello, World!"
Basic slicing
print(my_list[2:5]) # Output: [2, 3, 4] (elements from index 2 up to, but not including, index 5)
print(my_string[7:12]) # Output: World
Omitting start or stop
print(my_list[:4]) # Output: [0, 1, 2, 3] (from beginning to index 4, exclusive)
print(my_string[7:]) # Output: World! (from index 7 to the end)
1BPLC105B Python Programming
Using a step
print(my_list[::2]) # Output: [0, 2, 4, 6, 8] (every second element)
print(my_string[::-1]) # Output: !dlroW ,olleH (reversed string)
Negative indexing with slicing
print(my_list[-3:]) # Output: [7, 8, 9] (last three elements)
Key Characteristics of Slice operation
Slicing creates a new sequence; it does not modify the original.
Out-of-range indices in a slice are handled gracefully; Python adjusts them to legal values without raising
an IndexError. example
>>> word = "banana"
>>> word[3:158]
'ana'
String comparison
Python provides several ways to compare strings, primarily through comparison operators (==, >=,
and <=) and string methods.
String comparison involves evaluating the relationship between two strings by operators and returning the
Boolean result as output.
This can be done using various operators and methods, depending on the desired comparison type (e.g.,
equality, lexicographical order).
2. Lexicographical Comparison:
Operators like <, >, <=, and >= compare strings based on their lexicographical (alphabetical) order, using
the Unicode values of their characters.
The comparison proceeds character by character from left to right. The first differing character
determines the order.
Example 1:
str_a = "apple"
str_b = "banana"
str_c = "avocado"
print(str_a < str_b) # True (apple comes before banana)
print(str_a > str_c) # False (avocado comes after apple lexicographically because 'v' > 'p')
Example 2:
word="Zebra"
if word > "banana":
print("Your word, " + word + ", comes after banana.")
elif word < "banana":
print("Your word, " + word + ", comes before banana.")
1BPLC105B Python Programming
else:
print("Yes, we have no bananas!")
This is similar to the alphabetical order you would use with a dictionary, except that all the uppercase
letters come before all the lowercase letters. As a result.
"Your word, Zebra, comes before banana".
1. Mutable data types: In Python, mutable types can be changed after creation, for example like lists,
dictionaries.
2. Immutable data types: Immutable types cannot be altered once created. Example strings, tuples.
In Python, strings are indeed immutable data types. This means that once a string object is created, its
content cannot be changed.
It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a
character in a string. For example:
Example:
greeting = "Hello, world!"
greeting[0] = 'J' # ERROR!
print(greeting)
>>>Traceback (most recent call last):
File "<string>", line 2, in <module>
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.
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.
The solution here is to concatenate a new first letter onto a slice of the greeting. This operation does not
affect the original string.
Example:
Program Output
These operators are widely used for conditional checks, input validation, and searching within data
structures.
Example 1:
>>> "p" in "apple" >>> "ap" in "apple" >>> "a" in "a"
True True True
>>> "i" in "apple" >>> "pa" in "apple" >>> "apple" in "apple"
False False True
>>> "x" not in "apple" >>> "" in "a"
True True
Combining the in operator with string concatenation using +, we can write a function that removes all the
vowels from a string:
def remove_vowels(phrase):
vowels = "aeiouAEIOU"
string_sans_vowels = ""
for letter in phrase:
if [Link]() not in vowels:
string_sans_vowels += letter
return string_sans_vowels
A 'find' function
The find() method in Python is a string method used to locate the first occurrence of a specified substring
within a string.
It returns the lowest index in the string where the substring is found.
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.
Examples
Program Output
In the above examples, program 1 finds the first occurrence of the letter "e" in a given string, and the
second example finds text in the given sequence, the word "welcome".
Where in the text is the first occurrence of the letter "e" search only between positions 5 and 10 as found
in the third program. In the final program, If the value is not found, the find() method returns -1, but
the index() method will raise an error.
Example 1:
# The string to be processed
fruit = "banana"
# Initialize a counter variable to 0
count = 0
# Iterate through each character in the string
for char in fruit:
# Check if the current character is the target letter 'a'
if char == 'a':
# If it is, increment the counter
count += 1
# Print the final count
print(count) # Output = 3
Example 2:
word = 'raspberry'
count = 0
for letter in word:
if letter == 'r':
count = count + 1
print(count) # Output = 3
Example
my_string = "banana"
print(f"Number of 'a' in {my_string}': {my_string.count('a')}")
1BPLC105B Python Programming
Optional parameters
To find the locations of the second or third occurrence of a character in a string, we can modify
the find function, adding a third parameter for the starting position in the search string: Example
Example 1:
>>> phrase = "Well I never did said Alice"
>>> words = [Link]()
>>> words
['Well', 'I', 'never', 'did', 'said', 'Alice']
Example 2:
sentence = "Python is a powerful language"
words = [Link]()
print(words)
# Output: ['Python', 'is', 'a', 'powerful', 'language']
Example 3:
data = "apple,banana,orange"
fruits = [Link](',')
1BPLC105B Python Programming
print(fruits)
# Output: ['apple', 'banana', 'orange']
Example 1:
#Joining a list of strings without any separator (empty string)
characters = ["H", "e", "l", "l", "o"]
result_no_separator = "".join(characters)
print(result_no_separator)
# Output = Hello
Example 2:
#Joining a list of strings with a space as a separator
words = ["Python", "is", "fun"]
result_space = " ".join(words)
print(result_space) # Output = Python is fun
Example 3:
#Joining a list of strings with a comma and space as a separator
items = ["apple", "banana", "cherry"]
result_comma = ", ".join(items)
print(result_comma) # Output = apple, banana, cherry
Example 4:
#Joining a list of numbers (first convert them to strings)
numbers = [1, 2, 3, 4, 5]
#Using a list comprehension to convert numbers to strings
string_numbers = [str(num) for num in numbers]
result_numbers = "-".join(string_numbers)
print(result_numbers)
strip() method: This method is used to remove leading and trailing characters from a string. By default, it
removes whitespace characters (spaces, tabs \t, newlines \n). It returns a new string and does not modify
the original.
my_string = " Hello, World! \n"
cleaned_string = my_string.strip()
print(cleaned_string)
# Output: "Hello, World!"
Related Methods:
lstrip(): Removes leading (left-side) characters only. Example
# Removing leading whitespace
s1 = " Hello World!"
result1 = [Link]()
print(result1) # Output: "Hello World!"
# Removing specific leading characters
s2 = "zzzyxabc"
result2 = [Link]("xyz")
print(result2) # Output: "abc"
# Order of characters in 'chars' doesn't matter
s3 = "abccba"
result3 = [Link]("bac")
print(result3) # Output: ""
rstrip(): Removes trailing (right-side) characters only.
1BPLC105B Python Programming
Using f-string
The f-strings, also known as formatted string literals, is used to embed expressions inside string literals.
The "f" in f-strings stands for formatted and prefixing it with strings creates an f-string.
The curly braces {} within the string will then act as placeholders that is filled with variables, expressions,
or function calls.
Example: The following example illustrates the working of f-strings with expressions.
>>> item1_price = 2500
>>> item2_price = 300
>>> total = f'Total: {item1_price + item2_price}'
>>> print(total)
# The output of the above code is - Total: 2800
1BPLC105B Python Programming
Chapter 2- Tuples
But if we try to use item assignment to modify one of the elements of the tuple, we get an error: Example
So like strings, tuples are immutable. Once Python has created a tuple in memory, it cannot be changed.
Tuple assignment
Python has a very powerful tuple assignment feature: tuple packing and Unpacking
tuple packing: Tuple packing is the process of grouping multiple values into a single tuple. Examples
#Explicit packing using parentheses (optional)
my_tuple = ("apple", "banana", "cherry")
#Implicit packing without parentheses (also works)
another_tuple = 1, 2, 3, "four"
tuple unpacking: Tuple unpacking is the process of extracting the individual values from a tuple and
assigning them to separate variables.
Example
>>> bob = ("Bob", 19, "CS")
>>> (name, age, studies) = bob # tuple unpacking
>>> name output "bob"
>>> age output 19
>>> studies output "CS"
The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its
respective variable. Tuple assignment solves this problem neatly:
>>> (a, b) = (b, a)
Naturally, the number of variables on the left and the number of values on the right have to be the same:
1BPLC105B Python Programming
Example
>>> (one, two, three, four) = (1, 2, 3)
ValueError: need more than 3 values to unpack
def circle_stats(r):
"""Return (circumference, area) of a circle of radius r"""
circumference = 2 * [Link] * r
area = [Link] * r * r
return (circumference, area)
1BPLC105B Python Programming
Chapter 3- Lists
Introduction
Lists are built-in data types, used to store multiple values in a single variable.
A list is an ordered collection of values that begins with an opening square bracket and ends with a
closing square bracket, [].
Values inside the list are also called elements or items and are separated with commas. Example, A list
value looks like this: ['cat', 'bat', 'rat', 'elephant'].
List values
In Python, there are several ways to create a new list using square brackets [].
We can store and access values in a list using various methods:
Examples
>>> numbers = [10, 20, 30, 40]
>>> words = ["spam", "bungee", "swallow"]
>>> mixed_list = [1, "hello", 3.14, True]
Nested List: A nested list in Python is a list that contains other lists as its elements. Examples:
>>> stuffs = ["hello", 2.0, 5, [18, 20]]
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> my_list = ['a', 1, ['b', 2, ['c', 3]], True]
We can assign list values to variables or pass lists as parameters to functions:
>>> vocabulary = ["apple", "cheese", "dog"]
>>> numbers = [17, 123]
>>> an_empty_list = []
>>> print(vocabulary, numbers, an_empty_list)
["apple", "cheese", "dog"] [17, 123] []
Accessing elements
Accessing list elements in Python is primarily done through indexing and slicing.
The syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a
string - the index operator: []
Consider the list ['cat', 'bat', 'rat', 'elephant'] stored in a variable named spam.
The Python code spam[0] would evaluate to 'cat', and spam[1] would evaluate to "bat", and so on.
The integer inside the square brackets that follows the list is called an Index. (position or location of
elements in a list)
The first value in the list is at index 0, the second value is at index 1, the third value is at index 2, and so
on.
1BPLC105B Python Programming
The syntax for accessing the elements using the index operator: []. The expression inside the brackets
specifies the index. Remember that the indices start at 0.
Example
>>> numbers = [17, 123]
>>> numbers[0]
17
>>> numbers[9-8]
123
Indexes can only be integer values, not floats
>>> numbers[1.0]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: list indices must be integers, not floats
If you try to access or assign to an element that does not exist, you get a runtime error:
Example
>>> numbers = [17, 123]
>>> numbers[3]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
IndexError: list index out of range.
List length
The function len() returns the length of a list, which is equal to the number of its elements. Example
>>> vocabulary = ["apple", "cheese", "dog"]
>>> len(vocabulary)
# output is 3
>>> len(["car makers", 1, ["Ford", "Toyota", "BMW"], [1, 2, 3]])
# output is 4
List membership
The in and not in operators in Python are membership operators used to test whether a value or variable is
present in a sequence or collection.
They always return a Boolean value (True or False).
Examples
>>> my_list = [1, 2, 3, 4, 5]
>>> print(3 in my_list)
# Output: True
>>> print(10 in my_list)
# Output: False
>>> print(10 not in my_list)
# Output: True
>>> my_string = "hello world"
>>> print("world" in my_string)
# Output: True
>>> print("how" in my_string)
# Output: False
List operations
Concatenation Operator (+): This operator combines two or more lists into a new, single list. It
combines elements from both lists in the order they appear.
1BPLC105B Python Programming
Example
>>> first_list = [1, 2, 3]
>>> second_list = [4, 5, 6]
>>> both_lists = first_list + second_list
>>> both_lists
[1, 2, 3, 4, 5, 6]
Replication Operator (*): This operator creates multiple copies of a list and concatenates them together.
It takes the list and an integer as operands to specify the number of repetitions.
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
List slices
List slicing allows extracting a portion of a list, creating a new list containing a subset of the original
elements.
It utilises the slice operator, which is the colon :, within square brackets. []
Examples: Consider a list of numbers:
>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Get a specific range of elements: numbers[2:6] returns elements starting from index 2 up to (but not
including) index 6. # Output: [2, 3, 4, 5]
Get elements from the beginning to a specific index: numbers[:4] gets the first four elements. #
Output: [0, 1, 2, 3]
Get elements from a specific index to the end: numbers[5:] gets elements from index 5 to the end of the
list. # Output: [5, 6, 7, 8, 9]
Use a step size: numbers[::2] gets every second element of the entire list # Output: [0, 2, 4, 6, 8]
Use negative indexing: numbers[-3:-1] gets elements from the third-to-last (index 7) up to (but not
including) the last (index 9). # Output: [7, 8]
Reverse a list: numbers[::-1] uses a negative step to traverse the list in reverse order, a common Python
trick. # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
We can also remove elements from a list by assigning an empty list to them:
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3] = []
>>> a_list
['a', 'd', 'e', 'f']
We can add elements to a list by squeezing them into an empty slice at the desired location:
>>> a_list = ["a", "d", "f"]
>>> a_list[1:1] = ["b", "c"]
>>> a_list
['a', 'b', 'c', 'd', 'f']
>>> a_list[4:4] = ["e"]
>>> a_list
['a', 'b', 'c', 'd', 'e', 'f']
List deletion
The del statement removes an element from a list
>>> a = ["one", "two", "three"]
>>> del a[1]
>>> a
# Output ['one', 'three']
We can also use del with a slice to delete a sublist
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> del a_list[1:5]
>>> a_list
# Output ['a', 'f']
In one case, a and b refer to two different objects that have the same value. In the second case, they refer
to the same object.
We can verify this using the is operator, which checks if two references point to the same object:
>>> a is b # Output is True.
1BPLC105B Python Programming
In the above case, since strings are immutable, Python optimises resources by making two names that
refer to the same string value refer to the same object.
This is not the case with lists: for example #Values are the same
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b
True
>>> a is b
False # Objects are different
In the above case, a and b have the same value but do not refer to the same object. The state diagram
looks like this:
The primary difference is that the == operator checks for value equality, while the **is** operator
checks for object identity (same memory location).
Aliasing
In Python, aliasing occurs when two or more variables refer to the same object in memory. This means
the variables are aliases of each other.
This is particularly relevant when dealing with mutable objects like lists, dictionaries.
Changes made to a mutable object through one alias will be reflected in all other aliases, which can lead
to unexpected behaviour if not handled carefully.
How Aliasing Works
Python variables are not containers themselves; instead, they are references (or pointers) to objects in
memory. The assignment operator (=) binds a name to an object.
When we write b = a, you are not copying the value of a into b; you are making b point to the same object
that a points to.
You can verify if two variables are aliases using the built-in id() function, which returns the unique
memory address of an object, or the is operator, which checks for object identity:
Example
Program IDs of the Memory location
Because the same list has two different names, a and b, we say that it is aliased. Changes made with one
alias affect the other:
>>> a = [1, 2, 3]
>>> b = a # b is an alias of a
>>> b[0] = 999 # Mutates the shared list object
>>> print(a)
# Output: [999, 2, 3] a is also changed
Cloning lists
Cloning in Python refers to creating a copy of an object, rather than just a reference to the original object.
Cloning a list in Python creates a new, independent list object.
This distinction is crucial when you want to modify the copy without affecting the original.
The easiest way to clone a list is to use the slice operator: Example
>>> a = [1, 2, 3]
>>> b = a[:]
>>> b
# output [1, 2, 3]
Taking any slice of a creates a new list. In this case, the slice happens to consist of the whole list. So now
the relationship is like this:
Now we are free to make changes to b without worrying about changes in a.
>>> b[0] = 5
>>> a
#[1, 2, 3]
Example 1:
Program Output
Example 2:
Program Output
Example 3: Any list expression can be used in a for loop. The following example prints all the multiples
of 3 between 0 and 19.
Program Output
Example 4:
Since lists are mutable, we often want to traverse a list, changing each of its elements. The following
squares all the numbers in the list xs:
Program Output
xs = [1, 2, 3, 4, 5]
for i in range(len(xs)): >>> [1, 4, 9, 16, 25]
xs[i] = xs[i]**2
print(xs)
Example 5:
In this example, we are interested in both the value of an item, (we want to square that value), and its
index (so that we can assign the new value to that position). enumerate generates pairs of both (index,
value) during the list traversal.
1BPLC105B Python Programming
Program Output
Example 6:
In this next example to see more clearly how enumerate works:
Program Output
List parameters
When a list is passed as an argument to a function in Python, a reference to that list is passed, not a copy
or clone.
This means that the function receives a direct link to the original list object in memory.
Functions that take lists as arguments and change them during execution are called modifiers, and the
changes they make are called side effects.
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter change the same list
that the argument is referencing.
For example, the function below takes a list as an argument and multiplies each element in the list by 2:
Program Output
In the function above, the parameter stuff_list and the variable things are aliases for the same object. So
before any changes to the elements in the list, the state diagram, looks like this:
1BPLC105B Python Programming
Since the list object is shared by two frames, we drew it between them. If a function modifies the items of
a list parameter, the caller sees the change.
List methods
A method is the same thing as a function, except it is "called on" a value.
Each data type has its own set of methods. The list data type, for example, has several useful methods for
finding, adding, removing, and otherwise manipulating values in a list.
The dot operator can also be used to access built-in methods of list objects. Some of the useful list
methods are as follows:
index(), append(), insert(), extend()
remove(), sort(), reverse(), count(), pop()
1. index() method
It is a built-in list method in Python.
The index() method finds the index position of an element or an item in a list.
The index() method finds the first occurrence of the specified item in the list.
The index() method raises an error if the value/item is not found.
syntax of the index() in Python.
>>> list_name.index(element/Values/items)
Example 1:
012
>>> fruits = ['apple', 'banana', 'cherry']
>>> [Link]("cherry") # output is 2
Example 2:
>>> fruits [4, 55, 64, 32, 16, 32]
>>> [Link](32)
# output is 3, first occurrence in the list elements
Example 3: Find the position of 'cherry', but start the search at position 4
fruits = ['apple', 'banana', 'cherry', 'kiwi', 'mango', 'orange', 'cherry']
x = [Link]("cherry", 4)
print(x) # Output is 6
2. append() method
It is a built-in method in Python.
The append() method adds a single element to the end of the list.
This method modifies the original list in place and does not return a new list; instead, it returns None.
3. insert() method
The insert() method in Python is a built-in list method used to insert an element at a specific index within
a list.
Syntax: [Link](index position, element). The first argument to insert() is the index for the new value,
and the second argument is the new value to be inserted.
Example:
>>> spam = ['cat', 'dog', 'bat']
>>> [Link](1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']
4. extend() method
extend() method is used to add items from one list to the end of another list.
This method modifies the original list by appending all items from the given iterable.
Using extend() method is an easy and efficient way to merge two lists or add multiple elements at once.
Example:
>>> a=[1,2,3]
>>> b=[3,4,5,9]
>>> [Link](b)
>>> print(a) # output is [1,2,3,3,4,5,9]
The main difference between the append() and extend() methods in Python is that append() adds
a single element to the end of a list, while extend() adds multiple elements from an iterable to the end of
a list.
5. remove() method
The remove() method removes the first occurrence of the element with the specified value. Examples
Program output
6. pop() method
The pop() function removes the last element or the element based on the index given.
Example
Program output
7. count() method
The count() function in Python is a built-in method used to determine the number of occurrences of a
specific element within a sequence.
It can be applied to various sequence types, including strings, lists, and tuples.
Program output
numb = [7, 2, 2, 9, 2, 2, 2, 2, 8] 6
x = [Link](2)
print(x)
8. sort() method
The sort() method sorts the list in ascending order by default.
Example 1:
>>> spam = [2, 5, 3.14, 1, -7]
>>> [Link]()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> [Link]()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
Example 2:
Program output
9. reverse() method
The reverse() method is an in-built method in Python that reverses the order of elements in a list. It sorts
the list in descending order by default
1BPLC105B Python Programming
Example:
>>> fruits = ['apple', 'banana', 'cherry']
>>> [Link]()
>>> print(fruits)
['cherry', 'banana', 'apple']
Example:
def add_numbers(a, b):
"""
This pure function takes two numbers and returns their sum.
It is deterministic and has no side effects.
"""
return a + b
# Example usage:
result1 = add_numbers(5, 3)
print(f"The sum of 5 and 3 is: {result1}")
result2 = add_numbers(5, 3)
print(f"Calling with the same input again: {result2}")
Output
>>>The sum of 5 and 3 is: 8
Calling with the same input again: 8
Modifier or impure function: An impure function is 'influenced' by forces outside the function. With an
impure function, given the same arguments, there is no guarantee that it will return the same output. The
function below is not pure. This is because it is using a variable outside the function. Example
Program Output
num3=10 >>>40.0
def func(num1,num2):
x = (num1*num2)/num1*num3
return x
print(func(5,4))
split() method:
The split method divides a string into a list of words.
By default, any number of white space characters is considered a word boundary:
1BPLC105B Python Programming
join() method:
join() method reassembles a list of words into to string with a specified separator.
>>> a = "Hello, how are you?"
>>> b = [Link]() # Split by space
>>> c = "--".join(b) # Join with hyphen
>>> print(b) # output is ['Hello,', 'how', 'are', 'you?']
>>> print(c) # outputis Hello,--how--are--you?
The range() function: It generates a sequence of numbers, often used in loops for iteration. By default, it
creates numbers starting from 0 up to but not including a specified stop value.
Example
>>> range(9) # output is range(0, 9)
list(range()) function: In Python, range() is used to generate a sequence of numbers. When you wrap it
with list(), it converts that sequence into a list.
Example
>>> list(range(10)) # Output is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2,18)) # Output is [2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range (1,10,2)) # Output is [1, 3, 5, 7, 9]
>>> list(range (10,0,-2)) # Output is [10, 8, 6, 4, 2]
import random
sv = [Link]()
def sum1():
# Build a list of random numbers, then sum them """
xs = []
for i in range(10000000):
num = [Link](1000) # Generate one random number
[Link](num) # Save it in our list
tot = sum(xs)
return tot
def sum2():
# Sum the random numbers as we generate them """
tot = 0
for i in range(10000000):
num = [Link](1000)
tot += num
return tot
print(sum1())
print(sum2())
Output:
>>> 4996033058
4995426921
Nested lists
A nested list in Python is a list that contains other lists as its elements.
Example 1
>>> nested = ["hello", 2.0, 5, [10, 20]]
# In the above list, the element with index 3 is a nested list
Example 3:
>>> nested = ["hello", 2.0, 5, [10, 20]]
o If we output the element at index 3, we get:
o >>> print(nested[3]) # output [10, 20]
o >>> nested[3][1] # output is 20
1BPLC105B Python Programming
Matrices
Nested lists are often used to represent matrices. For example, the matrix:
Might be represented as: >>> mx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
o mx is a list with three elements, where each element is a row of the matrix.
o We can select an entire row from the matrix in the usual way:
>>> mx[1] # output is [4, 5, 6]
o can extract a single element from the matrix using the double-index form:
>>> mx[1][2] # output is 6
o The first index selects the row, and the second index selects the column.