[Go to site: main page, start]

0% found this document useful (0 votes)
4 views29 pages

Mod 2 Notes Python

This document provides an overview of strings in Python, detailing their characteristics, creation, and manipulation methods. It covers topics such as indexing, slicing, string comparison, immutability, and the use of membership operators. Additionally, it explains string methods like find() and demonstrates looping and counting techniques with strings.

Uploaded by

madhu010p
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)
4 views29 pages

Mod 2 Notes Python

This document provides an overview of strings in Python, detailing their characteristics, creation, and manipulation methods. It covers topics such as indexing, slicing, string comparison, immutability, and the use of membership operators. Additionally, it explains string methods like find() and demonstrates looping and counting techniques with strings.

Uploaded by

madhu010p
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

1BPLC105B Python Programming

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."""

A compound data type


 A data types that comprise smaller pieces is called a "compound data type".
 Compound data types in Python are data structures capable of holding multiple items or values, which
can be of different data types, within a single entity. 
 They provide ways to organise and manage collections of data.

Working with strings as single things


 Assigning a string to a variable is done with the variable name followed by an equal sign and the string.
Example: a=" hello world"
 String is also an object. Each string instance has its own attributes and methods.
 Example:
>>> our_string = "Hello, World!"
>>> all_caps = our_string.upper()
>>> all_caps
'HELLO, WORLD!'

 The upper() method in Python is a built-in string method used to convert all lowercase letters within a
string to their uppercase.

Working with the parts of a string


 In Python, strings are sequences of characters, and individual characters or substrings can be accessed
using indexing and slicing. 
 The indexing operator [] square brackets to select a single character or substring from a string.
 Python uses zero-based indexing, meaning the first character is at index 0, the second at index 1, and so
on.
 An index specifies a member of an ordered collection. It must be an integer.
 You can also use negative indexing, where -1 refers to the last character, -2 to the second-to-last, and so
forth.

 The syntax for accessing a character is string_name[index].


1BPLC105B Python Programming

 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. 

Traversal and the for loop


 In Python, traversal refers to the process of visiting each item or element within a data structure, such as
a string, list, tuple, or dictionary. 
 The for loop is a fundamental control flow statement in Python that facilitates this traversal.
1BPLC105B Python Programming

 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

prefixes = "JKLMNOPQ" Jack


suffix = "ack" Kack
for p in prefixes: Lack
print(p + suffix) Mack
Nack
Oack
Pack
Qack

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).

1. Equality and Inequality:


 The == operator checks for exact equality, considering case. It returns True if both strings have the same
characters in the same order, otherwise False. 
 The != operator checks for inequality, returning True if the strings are different, and False if they are
identical.
str1 = "All is Well"
str2 = "all is well"
str3 = "All in Well"
print(str1 == str2) # False (case-sensitive)
print(str1 == str3) # True
print(str1 != str2) # True

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".

Strings are immutable


 In Python, data types are categorized as either mutable or immutable, depending on whether their values
can be changed after they are created.

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

greeting = "Hello, world!" >>> Jello, world!


new_greeting = 'J' + greeting[1:]
print(new_greeting)

The 'in' and 'not in' operators


 In Python, in and not in are membership operators used to check if a value exists within a sequence or
collection. They return a Boolean value (True or False). 
 The in operator checks if a specified value is present within a sequence (like a list, tuple, string, or set)
 The not in operator checks if a specified value is not present within a sequence.
1BPLC105B Python Programming

 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

txt = "Hello, welcome to my world." 1


x = [Link]("e")
print (x)

txt = "Hello, welcome to my world." 7


x = [Link]("welcome")
print(x)

txt = "Hello, welcome to my world." 8


x = [Link]("e", 5, 10)
print(x)

txt = "Hello, welcome to my world." -1 Error


print([Link]("q"))
print([Link]("q"))
1BPLC105B Python Programming

 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.

Looping and counting


 Looping and counting in Python are fundamental concepts used for repetitive tasks and tracking
iterations or occurrences. 
 In Python, looping and counting are fundamental operations often performed together.
 The following program counts the number of times the letter a appears in a string, and is another example
of the counter pattern introduced in Counting digits:

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

Program using a user-defined function


def count_a(text):
count = 0
for letter in text:
if letter == 'a':
count += 1
return count
print(count_a("banana")) # Output = 3

The count() method:


In Python, the count() method is a built-in function 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.

Example
my_string = "banana"
print(f"Number of 'a' in {my_string}': {my_string.count('a')}")
1BPLC105B Python Programming

Out put Number of 'a' in banana : 3


my_list = [2, 1, 2, 2, 3, 2]
print(f"Number of 2s in the list: {my_list.count(2)}")
Out put = Number of 2s in the list: 4

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

def find2(haystack, needle, start):


for index, letter in enumerate(haystack[start:]):
if letter == needle:
return index + start
return -1
print(find2("banana", "a", 2)==3)

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 string.
 It returns the lowest index in the string where the substring is found.
 If the substring is not found, it returns -1.
 It can find substrings, not just single characters
 Example:
 >>> "banana".find("nan")
2
 It finds the first occurrence of the substring "nan" in 'banana'
 >>> "banana".find("na", 3)
4
 It finds the first occurrence of the substring "na" in 'banana' starts at the index 3.

String manipulation methods


 1. The split() method
 The split() method in Python is a string method used to divide a string into a list of substrings.
 The split method splits a single multi-word string into a list of individual words, removing all the
whitespace between them. (Whitespace means any tabs, newlines, or spaces.)
 This allows us to read input as a single string and split it into words.

 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']

2. The join() Method


 The join() method takes all items in an iterable and joins them into one string.
 The join() method in Python is a string method used to concatenate the elements of an iterable (such as a
list, tuple, or set) into a single string. 
 It uses the string on which it is called as a separator between the elements.

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)

3. The replace() method


 The replace() method searches a string for a specified character, and returns a new string where the
specified character(s) are replaced. 
 Syntax: [Link](old, new, count)

 Example 1: Replacing a character


word = "banana"
new_word = [Link]("a", "o")
print(new_word)
# Output: bonono

 Example 2: Replacing all occurrences


text = "Hello world, hello Python!"
new_text = [Link]("hello", "hi")
print(new_text)
# Output: hi world, hi Python!
1BPLC105B Python Programming

 Example 3: Replacing a limited number of occurrences:


sentence = "one two three one two three"
new_sentence = [Link]("one", "first", 1)
print(new_sentence)
# Output: first two three one two three

4. The isdigit() method.


 The isdigit() function in Python is a built-in string method used to check if all characters in a string are
digits.
 Example:
 #Returns True because all characters are digits
string1 = "12345"
print([Link]())
 #Returns False because of the letter 'a'
string2 = "123a45"
print([Link]())
 #Returns False because of the space
string3 = "12 345"
print([Link]())
 #Returns False because of the decimal point
string4 = "12.34"
print([Link]())
 #Returns False because of the negative sign
string5 = "-123"
print([Link]())
 #Returns True for a string with a Unicode superscript digit
string6 = "²³⁴"
print([Link]())

Other string methods


1. Case Conversion methods:
 upper(): Converts all characters in the string to uppercase.
 lower(): Converts all characters in the string to lowercase.
 capitalize(): Capitalises the first character of the string and converts the rest to lowercase.
 title(): Capitalizes the first letter of each word in the string.
 swapcase(): Swaps the case of all characters (uppercase becomes lowercase, lowercase becomes
uppercase).

2. Searching and Checking:


 find(substring): Returns the lowest index of the substring if found, otherwise -1.
 index(substring): Returns the lowest index of the substring if found, otherwise raises a ValueError.
 startswith(prefix): Checks if the string starts with the specified prefix.
 endswith(suffix): Checks if the string ends with the specified suffix. 
 isalnum(): Returns True if all characters are alphanumeric.
 isalpha(): Returns True if all characters are alphabetic.
 isdigit(): Returns True if all characters are digits.
 islower(): Returns True if all case characters are lowercase.
 isupper(): Returns True if all cased characters are uppercase.
 isspace(): Returns True if all characters are whitespace.
1BPLC105B Python Programming

3. Modification and Formatting:


 strip(): Removes leading and trailing whitespace (or specified characters).
 lstrip(): Removes leading whitespace (or specified characters).
 rstrip(): Removes trailing whitespace (or specified characters).
 replace(old, new): Replaces all occurrences of old with new.
 split(delimiter): Splits the string into a list of substrings based on a delimiter.
 center(width, fillchar): Centers the string within a specified width, padding with fillchar (defaults to
space).

Cleaning up your strings


Cleaning up strings in Python involves removing or modifying unwanted characters, spaces, or
formatting to standardize the text.
 Strings that contain punctuation, or tab and newline characters. To count word frequencies or check the
spelling of each word, we'd prefer to strip off these unwanted characters. 

 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!"

 Removing Specific Characters:


 To provide an optional argument to strip() specifying a set of characters to remove from the beginning
and end of the string.
 The function will remove any of these characters until it encounters a character not in the specified set.
data = "---Python---"
cleaned_data = [Link]('-')
print(cleaned_data)
# Output: "Python"symbols = "###!@Text#!###"
cleaned_symbols = [Link]('!#$@')
print(cleaned_symbols)
# Output: "Text"

 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

The string format method


 The easiest and most powerful way to format a string in Python is to use the format method.
 String formatting in Python is the process of building a string representation dynamically by inserting
the value of numeric expressions in an already existing string. 
 Python's string concatenation operator doesn't accept a non-string operand. Hence, Python offers
following string formatting techniques –
 Using % operator
 Using format() method of str class
 Using f-string
 Using String Template class

Using format() method


 It is a built-in method of str class. The format() method works by defining placeholders within a string
using curly braces {}.
 These placeholders are then replaced by the values specified in the method's arguments.
 Example: In the below example, we are using format() method to insert values into a string dynamically. 
>>> str = "Welcome to {}"
>>> print([Link]("Tutorialspoint"))
Welcome to Tutorialspoint

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

Tuples are used for grouping data


 A tuple is a built-in data type in Python.
 Tuples are used to store multiple data items in a single variable. Or It is used to store sequences of data.
 A tuple is created by placing all the items inside parentheses (), separated by commas. Example:
 mytuple = ("apple", "banana", "cherry")
 year_born = ("Paris Hilton", 1981)
 Julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress")
 The creation of an empty tuple is done like this: empty_tuple = ()
 The creation of a single-element tuple is done like this: single_tuple = (36,)

Key Characteristics of Tuples:


a. Ordered: Items have a defined order that does not change.
b. Immutable (Unchangeable): Once a tuple is created, you cannot change, add, or remove items.
c. Allow Duplicates: Because they are indexed, tuples can have items with the same value.
d. Indexed: Items are accessed using zero-based integer indices, similar to lists and strings.
e. Heterogeneous: A single tuple can contain items of different data types (e.g., strings, integers, and
floats).
 Tuples support the same sequence operations as strings. The index operator selects an element from a
tuple. Example
>>> Julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress")
>>> Julia[3]
# output Duplicity

 But if we try to use item assignment to modify one of the elements of the tuple, we get an error: Example

>>> julia[0] = "x"


TypeError: 'tuple' object does not support item assignment

 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

Tuples as return values


 Functions can always only return a single value.
 In Python, a function can return more than one value at a time using commas.
 These values are usually returned as a tuple.
 This is useful when a function needs to give back several related results together.
 For example, we could write a function that returns both the area and the circumference of a circle of
radius r:

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']. 

The key features of lists in Python are:


1. Ordered: Items in a list have a defined order, which is preserved.
2. Mutable (Changeable): We can modify, add, or remove elements from a list after it has been created.
3. Allows Duplicates: Because lists are index-based, they can contain multiple items with the same value.
4. Heterogeneous (Mixed Data Types): A single list can store items of different data types simultaneously.
5. Indexable: Elements are accessed using a zero-based index system.

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]

Lists are mutable


 Lists are mutable, which means we can change their elements after they have been created.
 Using the index operator on the left side of an assignment, we can update one of the elements. Examples
>>> fruit = ["banana", "apple", "quince"]
>>> fruit[0] = "pear"
>>> fruit[2] = "orange"
>>> fruit
['pear', 'apple', 'orange']
 An assignment to an element of a list is called item assignment. Item assignment does not work for
strings:
>>> my_string = "TEST"
>>> my_string[2] = "X"
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'str' object does not support item assignment
 With the slice operator, we can update a whole sublist at once:
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3] = ["x", "y"]
>>> a_list
['a', 'x', 'y', 'd', 'e', 'f']
1BPLC105B Python Programming

 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']

Objects and references


 In Python, all data is represented as objects, and variables are essentially references (or names) that
point to these objects.
 This concept is fundamental to understanding how Python handles data and memory. An object is a piece
of data stored in memory. 
 Every object has an identity (its memory address, obtainable with id()), a type (e.g., integer, string, list,
custom class instance), and a value. 
 When you execute n = 300, Python creates a single integer object with the value 300 in memory.
 Each object is assigned a unique identifier, which you can check using the built-in id() function.
 References
 A reference is a link or pointer to an object. A variable name is essentially a symbolic name (a "sticker"
in one analogy) that refers to an object.
 Assignment: When we make an assignment, we are binding a name to an object. For example:
>>> a = "banana"
>>> b = "banana"
 In the above example, both a and b are references pointing to the same string object in memory.

 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

>>> a = [1, 2, 3] >>> 1849914787136


>>> b = a 1849914787136
>>> a is b
True
>>> print(id(a))
>>> print(id(b))

 In this case, the state diagram looks like this:


1BPLC105B Python Programming

 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]

Lists and for loops


 In Python, for loops are commonly used to iterate over sequences.
 A for loop provides a concise way to process each item within a list.
 The basic syntax involves a loop variable that takes on the value of each item in the list during each
iteration.
 The generalised syntax of a for loop is:
for <VARIABLE> in <LIST>:
<BODY>
1BPLC105B Python Programming

 Example 1:
Program Output

x = ["apple", "banana", "cherry"] apple


for fruit in x: banana
print(fruit) cherry

 Example 2:
Program Output

friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", Joe


"Paris"] Zoe
for friend in friends: Brad
print(friend) Angelina
Zuki
Thandi
Paris

 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

for number in range(20): 0


if number % 3 == 0: 3
print(number) 6
9
12
15
18

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

xs = [1, 2, 3, 4, 5] >>> The index are: 0


for (i, val) in enumerate(xs): The index are: 1
xs[i] = (val**2) The index are: 2
print("The index are:", i) The index are: 3
print("The values are:", xs) The index are: 4
The values are: [1, 4, 9, 16, 25]

Example 6:
In this next example to see more clearly how enumerate works:
Program Output

for (i, v) in enumerate(["banana", "apple", "pear", "lemon"]): 0 banana


print(i, v) 1 apple
2 pear
3 lemon

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

def double_stuff(stuff_list): >>> [4, 10, 18]


# Overwrites each element in a list with double its value.
for (index, stuff) in enumerate(stuff_list):
stuff_list[index] = 2 * stuff
things = [2, 5, 9]
double_stuff(things)
print(things)

 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.

 Example 1: Add a single element to the end of the list:


>>> fruits = ['apple', 'banana', 'cherry']
>>> [Link]("orange")
>>> fruits # output is ['apple', 'banana', 'cherry', 'orange']

 Example 2: Add a list to a list:


>>> a = ["apple", "banana", "cherry"]
>>> b = ["Ford", "BMW", "Volvo"]
>>> [Link](b)
>>> print(a)
['apple', 'banana', 'cherry', ["Ford", "BMW", "Volvo"]]
1BPLC105B Python Programming

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

list1 = [1, 3, 2, 4] >>>[1, 3, 4]


[Link](2)
print(list1)

list1 = [1, 3, 2, 4, 2, 5] >>>[1, 3, 4, 2, 5]


[Link](2)
print(list1)

list1 = [4, 5, True, [3, 2], True, 4, 2, 5] >>>[4, 5, True, True, 4, 2, 5]


[Link]([3, 2])
print(list1)

6. pop() method
 The pop() function removes the last element or the element based on the index given.
 Example
Program output

fruits = ['apple', 'banana', 'cherry'] ['apple', 'cherry']


[Link](1)
print(fruits)
1BPLC105B Python Programming

fruits = ['apple', 'banana', 'cherry'] ['apple', 'banana']


[Link]() (last element is removed)
print(fruits)

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

fruits = ["apple", "cherry", "banana", "cherry"] 2


x = [Link]("cherry")
print(x)

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

numbers = [5, 2, 8, 1, 9] >>>[1, 2, 5, 8, 9]


[Link]() # Sorts in-place
print(numbers)

words = ["banana", "appllle", "cherry"] >>>['banana', 'cherry', 'appllle']


[Link](key=len) # Sorts by length
print(words)

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']

Pure functions and Modifiers


 Pure functions: A pure function always produces the same output for the same input and has no "side
effects," meaning it doesn't change any external state or data. A function is considered a Pure Function if
it fulfills the following two conditions: 
1. It always returns the same result for the given inputs, and its results purely depend on the inputs passed.
2. It has no side effects, means it does not modify any state of the caller entity.

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))

Strings and lists


 Two of the most useful methods on strings involve conversion to and from lists of substrings. They
are split() and join() methods

 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

>>> song = "The rain in Spain..."


>>> words = [Link]()
>>> words
['The', 'rain', 'in', 'Spain...']
 An optional argument called a delimiter can be used to specify which string to use as the boundary
marker between substrings.
 The following example uses the string ai as the delimiter: Notice that the delimiter doesn't appear in the
result.
>>> song = "The rain in Spain..."
>>> [Link]("ai")
['The r', 'n in Sp', 'n...']

 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?

list and range


 In Python, list and range are distinct but often used together to manage sequences of data.
 The list() function creates a list object. Python has a built-in type conversion function called list that tries
to turn whatever you give it into a list.
>>> letters = list("Crunchy Frog")
>>> letters
['C', 'r', 'u', 'n', 'c', 'h', 'y', ' ', 'F', 'r', 'o', 'g']
>>> "".join(letters)
'Crunchy Frog'

 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]

Looping and lists


 Computers are useful because they can repeat computation, accurately and fast. So loops are going to be a
central feature of almost all programs. 
 Lists are useful if you need to keep data for later computation.
 Here are two functions that both generate ten million random numbers and return the sum of the numbers.
They both work.
1BPLC105B Python Programming

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 2: Matrix is a list of lists.


matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
o To access elements in the above example: Use two indices: [row][column]
o print(matrix[0]) # First row -> [1, 2, 3]
o print(matrix[1][2]) # Element 6

 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.

You might also like