0% found this document useful (0 votes)
2 views

Python Unit2

The document provides a comprehensive overview of arrays in Python, including when to use them, how to define and manipulate them, and various operations such as indexing, concatenation, and searching. It also covers functions, including defining, calling, passing arguments, and using lambda functions, along with built-in functions like map(), reduce(), and filter(). Additionally, it explains the scope of variables and the use of default and keyword arguments.

Uploaded by

sanketsutar6061
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Unit2

The document provides a comprehensive overview of arrays in Python, including when to use them, how to define and manipulate them, and various operations such as indexing, concatenation, and searching. It also covers functions, including defining, calling, passing arguments, and using lambda functions, along with built-in functions like map(), reduce(), and filter(). Additionally, it explains the scope of variables and the use of default and keyword arguments.

Uploaded by

sanketsutar6061
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Unit 2

When to Use Arrays


• Use arrays when storing multiple values of the
same type.
• They provide better performance compared to
lists for large data.
• Useful for numerical operations and data
processing.
• Preferred when using libraries like NumPy for
scientific computing.
Defining an Array

• arrays can be created using the array module.


• Lists can also be used as dynamic arrays.
• Syntax: array.array(typecode, [elements])

Example:
import array
arr = array.array('i', [10, 20, 30])
print(arr)
• Repetition operator: makes multiple copies of a
arrayand joins them together
• The * symbol is a repetition operator when applied to a
sequence and an integer
• Sequence is left operand, number is right
• General format: list * n
• numbers = [0] * 5
• numbers = [1, 2, 3] * 3
• print(numbers)
• You can iterate using a for loop

• Format: for x in array:


for variable in array:
statement
statement

Example :
numbers = [1, 2, 3, 4]
for num in numbers:
print(num)
Indexing
• Index: a number specifying the position of an
element
• Enables access to individual element in list
• Index of first element in the list is 0, second
element is 1, and n’th element is n-1
• Negative indexes identify positions relative to the
end of the list
• The index -1 identifies the last element, -2 identifies the
next to last element, etc.
my_list = [10, 20, 30, 40]
print(my_list[0], my_list[1], my_list[2], my_list[3])

OR

index = 0
while index < 4:
print(my_list[index])
index += 1
my_list = [10, 20, 30, 40]
print(my_list[−1], my_list[−2], my_list[−3], my_list[−4])

my_list = [10, 20, 30, 40]


index = 0
while index < 5:
print(my_list[index])
index += 1
The len function
• An IndexError exception is raised if an invalid index
is used
• len function: returns the length of a sequence such
as a array
• Example: size = len(array)
• Returns the number of elements in the array, so the index
of last element is len(list)-1
• Can be used to prevent an IndexError exception when
iterating over a array with a loop
my_list = [10, 20, 30, 40]
size = len(my_list)

my_list = [10, 20, 30, 40]


index = 0
while index < len(my_list):
print(my_list[index])
index += 1
names = ['Jenny', 'Kelly', 'Chloe', 'Aubrey']
for index in range(len(names)):
print(names[index])
• Mutable sequence: the items in the sequence
can be changed
• array are mutable, and so their elements can be
changed
• An expression such as
• array[1] = new_value can be used to
assign a new value to a list element
• Must use a valid index to prevent raising of an
IndexError exception
Concatenat
• Concatenate: join two things together
• The + operator can be used to concatenate
two lists
– Cannot concatenate a array with another data type,
such as a number
• The += augmented assignment operator can
also be used to concatenate array
• a=[1,2,3]
b=[2,3,4]
print(a+b)
s=['p','y','t','h','o','n']
print(s)

print(s[1:3])

print(s[2:])

print(s[:-5])

print(s[:])

print(s[::-1])
Finding Items with the in Operator
• You can use the in operator to determine whether an item
is contained in a array
• General format: item in array
• Returns True if the item is in the array or False if it is not in the list
• Similarly you can use the not in operator to determine
whether an item is not in a list
streaming = ['netflix', 'disney+', 'appletv+']
platform = 'amazon'
if platform in streaming:
print('amazon is in the streaming service business')
else:
print('It does not include')
Finding the Length of an Array

• Use the len() function to get the number of


elements in an array.

Example:
arr = [1, 2, 3, 4, 5]
print(len(arr)) # Output: 5
Searching in an Array

• Use the 'in' keyword to check if an element


exists.
• Use index() method to find the position of an
element.

Example:
arr = [5, 10, 15, 20]
print(arr.index(15)) # Output: 2
Operations on Arrays

• Appending: arr.append(value)
• Removing: arr.remove(value)
• Reversing: arr.reverse()
• Sorting: arr.sort()

Example:
arr = [3, 1, 4, 2]
arr.sort()
print(arr) # Output: [1, 2, 3, 4]
Defining Functions
• Functions are blocks of reusable code.
• Defined using the 'def' keyword followed by a function name.

Syntax:

def function_name(parameters):

def greet():
print('Hello, World!')

greet()

# Output: Hello, World!


Calling Functions
• A function is executed when it is called.
• Call a function using its name followed by parentheses.

Example:
def add():
a=5
b=3
c=a + b
print(c)

add()

# Output: 8
Passing Arguments
• Arguments are values passed to a function.
• Functions can take multiple arguments.

Example:
def multiply(a, b):
mult=a * b
print(mult)
multiply(4, 6)

# Output: 24
Keyword Arguments
• Arguments can be passed using key-value
pairs.
• Allows passing arguments in any order.

Example:
def greet(name, age):
print(f'Hello {name}, you are {age} years old!')

greet(age=25, name='Alice')
Default Arguments
• Assign default values to function parameters.
• Useful when some parameters have common
default values.

Example:
def greet(name='Guest'):
print(f'Hello, {name}!')

greet() # Output: Hello, Guest!


greet('Alice') # Output: Hello, Alice!
Scope and Lifetime of Variables
Scope determines where a variable can be accessed.
Local variables exist inside functions.
Global variables exist outside functions.

Example:
x=5 #Global Variable
def func():
x = 10 # Local variable
print(x)
Anonymous / Lambda Functions
• A lambda function is a small anonymous function.
• An anonymous function is a function without a name.
• A lambda function can take any number of arguments, but
can only have one expression.
• Syntax
lambda arguments : expression

Used for short, simple functions.


Example:
square = lambda x: x * x
print(square(5)) # Output: 25

x is the input to the function.


x * x is what the function does — it multiplies x
by itself.
So square becomes a function that returns the
square of a number.
• Example
Add 10 to argument a, and return the result:
x = lambda a : a + 10

print(x(5))

• x = lambda a, b : a * b

print(x(5, 6))

• x = lambda a, b, c : a + b + c

print(x(5, 6, 2))
Why Use Lambda Functions?
• The power of lambda is better shown when you use them as
an anonymous function inside another function.
Say you have a function definition that takes one argument, and
that argument will be multiplied with an unknown number:

def myfunc(n):

return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))
map() Function
• map() applies a function to all items in an iterable.
• The map() function is used to apply a given function to
every item of an iterable, such as a list or tuple, and
returns a map object (which is an iterator).
• Returns a map object that can be converted to a list.
• Syntax:
map(function, iterable)
• s = ['1', '2', '3', '4']
res = map(int, s)
print(list(res))

Syntax of the map() function


map(function, iterable)

Parameter:

● function: The function we want to apply to every element of the


iterable.
● iterable: The iterable whose elements we want to process.

Note: We can also pass multiple iterables if our function


accepts multiple arguments.
Converting map object to a list
• By default, the map() function returns a map object, which is an
iterator.
• In many cases, we will need to convert this iterator to a list to
work with the results directly.
Example: Let’s see how to double each elements of the given list.

a = [1, 2, 3, 4]

# Using custom function in "function" parameter


# This function is simply doubles the provided number
def double(val):
return val*2

res = list(map(double, a))


print(res)
map() with lambda
We can use a lambda function instead of a custom function with
map() to make the code shorter and easier.

a = [1, 2, 3, 4]
# Using lambda function in "function" parameter
# to double each number in the list
res = list(map(lambda x: x * 2, a))
print(res)
Using map() with multiple iterables
We can use map() with multiple iterables if the function we are
applying takes more than one argument.
Example: In this example, map() takes two iterables (a and b)
and applies the lambda function to add corresponding elements
from both lists.

a = [1, 2, 3]
b = [4, 5, 6]
res = map(lambda x, y: x + y, a, b)
print(list(res))
#Calculate fahrenheit from celsius
celsius = [0, 20, 37, 100]
fahrenheit = map(lambda c: (c * 9/5) + 32,
celsius)
print(list(fahrenheit))
reduce() Function
• reduce() applies a function cumulatively to all elements.
• The reduce(fun,seq) function is used to apply a particular function
passed in its argument to all of the list elements mentioned in the
sequence passed along.
• Needs to be imported from functools module.
• Syntax:
from functools import reduce
reduce(function, iterable)

Example:
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # Output: 24
from functools import reduce

# Function to add two numbers


def add(x, y):
return x + y

a = [1, 2, 3, 4, 5]
res = reduce(add, a)

print(res) # Output: 15

• Explanation:
The reduce() function applies add() cumulatively to the elements in numbers.
First, 1 + 2 = 3. Then, 3 + 3 = 6. And so on, until all numbers are processed.
The final result is 15.
Syntax of reduce()

functools.reduce(function, iterable[, initializer])

● function: A function that takes two arguments and


performs an operation on them.
● iterable: An iterable whose elements are processed by the
function.
● initializer (optional): A starting value for the operation. If
provided, it is placed before the first element in the
iterable.

The reduce() function is part of the functools module, so you


need to import it before use.
Using reduce() with lambda
When paired with a lambda function, reduce() becomes a
concise and powerful tool for aggregation tasks like summing,
multiplying or finding the maximum value.

from functools import reduce


# Summing numbers with reduce and lambda
a = [1, 2, 3, 4, 5]
res = reduce(lambda x, y: x + y, a)
print(res)
Using reduce() with operator functions
reduce() can also be combined with operator functions to achieve the similar
functionality as with lambda functions and makes the code more readable.

import functools
# importing operator for operator functions
import operator
# initializing list
a = [1, 3, 5, 6, 2]
# using reduce with add to compute sum of list
print(functools.reduce(operator.add, a))
# using reduce with mul to compute product
print(functools.reduce(operator.mul, a))
# using reduce with add to concatenate string
print(functools.reduce(operator.add, ["geeks", "for", "geeks"]))
filter() Function
• filter() selects elements based on a condition.
• Returns a filter object that can be converted to a list.
• Syntax:
filter(function, iterable)
• function: A function that returns True or False.
• iterable: The sequence of elements to filter.

Example:
nums = [1, 2, 3, 4, 5]
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums) # Output: [2, 4]
What does filter() do?

filter() is a built-in Python function.

It takes two things:
1. A function (our lambda function that checks for even
numbers)
2. A list (nums)

● It goes through the list and keeps only the values where
the function returns True (in this case, the even numbers).
ages = [5, 12, 17, 18, 24, 32]

def myFunc(x):
if x < 18:
return False
else:
return True

adults = filter(myFunc, ages)

for x in adults:
print(x)

You might also like