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

Python Unit II

The document covers key concepts of Object Oriented Programming and Control Structures in Python, including sequence types such as mutable and immutable sequences, and their operations. It explains the use of built-in functions like map() for applying functions to iterables, along with examples of manipulating lists, strings, and tuples. Additionally, it discusses control structures, error checking, and the importance of indexing and slicing in sequence operations.

Uploaded by

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

Python Unit II

The document covers key concepts of Object Oriented Programming and Control Structures in Python, including sequence types such as mutable and immutable sequences, and their operations. It explains the use of built-in functions like map() for applying functions to iterables, along with examples of manipulating lists, strings, and tuples. Additionally, it discusses control structures, error checking, and the importance of indexing and slicing in sequence operations.

Uploaded by

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

Unit II

Object Oriented Programming and Control Structure


Sequences, Mapping and Sets; Dictionaries; Classes: Classes and Instances; Inheritance;
Exceptional Handling; Module: Built-in modules & user-defined module; Introduction to
Regular Expressions using “re” module; pathlib function for file system. Control Structure;
Selection Control; If Statement; Indentation in Python; Multi-Way Selection; Iterative
Control; While Statement; Input Error Checking; Infinite Loops: Definite vs. Indefinite
Loops

In Python programming, sequence types are fundamental data structures that hold an ordered
collection of items. The main sequence types include Lists, Strings, Tuples, and Range objects.
These data structures allow us to access their elements through indexing and iteration.

Sequence Types in Python

Sequence types in Python are categorized into two main types: mutable and immutable
sequences.

Mutable Sequence Types

These sequences can be changed after their creation. You can modify elements, add new
elements, and remove existing ones.

Lists: A mutable, ordered collection of items that can store different data types.

Byte Arrays: A mutable sequence of bytes, used for handling binary data.

bytearray() function - Python

The bytearray() function in Python creates a mutable sequence of bytes, which is essentially an
array of integers in the range 0 to 255 (representing byte values). Unlike the immutable bytes
type, bytearray allows us to modify its contents after creation, making it useful for tasks like
binary data manipulation, file I/O, or network programming. It’s a built-in function that returns a
bytearray object
Arrays: A collection of items similar to lists, but optimized for numeric operations and storing
elements of the same data type.

# List example

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

my_list.append(60)

print("After append:", my_list)

my_list.remove(10)

print("After remove:", my_list)

After append: [10, 20, 30, 40, 50, 60]


After remove: [20, 30, 40, 50, 60]

Byte array

# Create a bytearray from a string


ba = bytearray("Geeks for geeks!", "utf-8")

print(ba) # Output: bytearray(b'geeks for geeks!')

# Modify the bytearray


ba[1] = 105 # 'i' in ASCII is 105
print(ba)

Output
bytearray(b'Geeks for geeks!')
bytearray(b'Gieks for geeks!')
# UTF-8 stands for Unicode Transformation Format – 8-bit.
It is a character encoding system used to convert characters such as letters, numbers, symbols, and
emojis into bytes that computers can store and process.
Their UTF-8/ASCII byte values are:

G → 71

e → 101
e → 101
k → 107
s → 115

Python indexing starts from 0:

Index: 0 1 2 3 4
G e e k s
ba[1]

refers to the second character, which is:

We replace it with byte value 105.

ASCII value:

105 → i

Immutable Sequence Types

These sequences cannot be changed once created. Any operation that appears to
modify them actually creates a new sequence.

Tuples: Ordered collections of objects that are immutable.


Strings: Sequences of characters enclosed in single ('') or double ("")
quotes.
Range Objects: Immutable sequences of numbers commonly used for looping.
Example
# Tuple example
my_tuple = (10, 20, 30, 40, 50)
print("Element at index 3:", my_tuple[3])

new_tuple = my_tuple + (60, 70)


print("New tuple:", new_tuple)

# String example
my_string = "Tutorials Point"
print("Character at index 4:", my_string[4])

new_string = my_string + " Python"


print("New string:", new_string)

# Range example
my_range = range(1, 6)
print("Range elements:", list(my_range))
Element at index 3: 40
New tuple: (10, 20, 30, 40, 50, 60, 70)
Character at index 4: r
New string: Tutorials Point Python
Range elements: [1, 2, 3, 4, 5]

Common Sequence Operations


Python provides several built−in operations that work with all sequence types.
Here are the most commonly used ones.

Membership Operators
Membership operators (in and not in) check if an element exists in a
sequence ?

Example

languages = ['java', 'python', 'c++']


print('python' in languages)
print('javascript' not in languages)

o/p
True
True

Concatenation and Repetition


Most sequence types support concatenation and repetition operations ?

Exapmle

list1 = [10, 20, 30]


list2 = [40, 50]

# Concatenation
result = list1 + list2
print("Concatenated:", result)

# Repetition
repeated = list1 * 3
print("Repeated:", repeated)

O/P

Concatenated: [10, 20, 30, 40, 50]


Repeated: [10, 20, 30, 10, 20, 30, 10, 20, 30]
Indexing and Slicing

Indexing accesses individual elements using their position (starting from 0).
Slicing extracts subsequences using start, stop, and step values ?

Example

items = ['a', 'b', 'c', 'd', 'e']

# Indexing
print("Element at index 2:", items[2])

# Slicing
print("Slice [1:4]:", items[1:4])

# Slicing with step


numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Every second element:", numbers[1:8:2])

O/P

Element at index 2: c
Slice [1:4]: ['b', 'c', 'd']
Every second element: [1, 3, 5, 7]

Length, Search, and Count


These operations help you analyze sequence contents ?

Example

numbers = [1, 5, 4, 5, 3, 20, 12, 5, 43]

print("Length:", len(numbers))
print("Index of 12:", [Link](12))
print("Count of 5:", [Link](5))

O/P
Length: 9
Index of 12: 6
Count of 5: 3

Mutable Sequence Operations

These operations work only with mutable sequences like lists and byte arrays ?

Example

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

# Append element
[Link](60)
print("After append:", data)

# Pop element at index 1


removed = [Link](1)
print("Popped:", removed)
print("After pop:", data)

# Remove element by value


[Link](40)
print("After remove:", data)

O/P

After append: [10, 20, 30, 40, 50, 60]


Popped: 20
After pop: [10, 30, 40, 50, 60]
After remove: [10, 30, 50, 60]

Python map() function




map() function in Python applies a function to every element of one


or more iterables and returns a map object (iterator) containing the
transformed results. It is commonly used for element-wise
operations and can often replace explicit loops with shorter and
more readable code.
Let's start with a simple example of using map() to convert a list of
strings into a list of integers.
s = ['1', '2', '3', '4']
res = map(int, s)
print(list(res))

Output
[1, 2, 3, 4]
Explanation: map() applies int() to each element in 's' which
changes their datatype from string to int.
Note: map() returns a lazy iterator, which means values are
generated only when needed. Once a map object is consumed, it
cannot be reused without creating a new one.

Syntax
map(function, iterable,...)
Parameters:
 function: The function to apply to every element of the
iterable.
 iterable: One or more iterable objects (list, tuple, etc.)
whose elements will be processed.
Note: You can pass multiple iterables if the function accepts
multiple arguments.

Converting map object to a list


By default, map() function returns a map object. In many cases, we
may need to convert this iterator to a list to work with the results
directly.
Example: Let's see how to double each element of the given list.
def double(val):
return val * 2

a = [1, 2, 3, 4]
res = list(map(double, a))
print(res)

Output
[2, 4, 6, 8]
Explanation:
 map(double, a) applies double() to each element in 'a'.
 list() converts the map object to a list.
Using map() with Tuples
map() works with any iterable, including tuples. The following
example increments each element of a tuple by 1.
nums = (1, 2, 3)
res = tuple(map(lambda x: x + 1, nums))
print(res)

Output
(2, 3, 4)
Explanation:
 lambda x: x + 1 increments each element by 1.
 map() applies this transformation to every element in the
tuple nums.
 tuple() converts the resulting map object back into a tuple.
String Manipulation with map()

Converting strings to Uppercase

This example shows how we can use map() to convert a list of


strings to uppercase.
fruits = ['apple', 'banana', 'cherry']
res = map([Link], fruits)
print(list(res))

Output
['APPLE', 'BANANA', 'CHERRY']
Explanation: [Link] method is applied to each element in the
list fruits using map(). The result is a list of uppercase versions of
each fruit name.

Extracting first character from strings

In this example, we use map() to extract the first character from


each string in a list.
words = ['apple', 'banana', 'cherry']
res = map(lambda s: s[0], words)
print(list(res))
Output
['a', 'b', 'c']
Explanation: lambda s: s[0] extracts first character from each string
in the list words. map() applies this lambda function to every
element, resulting map object is converted to a list of the first
characters using list().

Removing whitespaces from strings

In this example, We can use map() to remove leading and trailing


whitespaces from each string in a list.
s = [' hello ', ' world ', ' python ']
res = map([Link], s)
print(list(res))

Output
['hello', 'world', 'python']
Explanation: [Link] method removes leading and trailing
whitespaces from each string in list strings and map() applies
[Link]() to each element.
Real World Example
In this example, we use map() to convert a list of temperatures
from Celsius to Fahrenheit.
celsius = [0, 20, 37, 100]
fahrenheit = map(lambda c: (c * 9/5) + 32, celsius)
print(list(fahrenheit))

Output
[32.0, 68.0, 98.6, 212.0]
Explanation:
 lambda c: (c * 9/5) + 32 converts each Celsius temperature
to Fahrenheit using standard formula.
 map() function applies this transformation to all items in
the list celsius.

You might also like