Array As List, Operation&lamda Function in Python
Array As List, Operation&lamda Function in Python
A lambda function can take any number of arguments, but can only have one expression.
Syntax
x = lambda a : a + 10
print(x(5))
Example
x = lambda a, b : a * b
print(x(5, 6))
Example
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
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:
Examp1
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Output:22
Exampl2:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Output:22
33
for x in cars:
print(x)
Output:-
Ford
Volvo
BMW
Adding Array Elements
cars.append("Honda")
print(cars)
Output:-
You can use the pop() method to remove an element from the array.
cars.pop(1)
print(cars)
Output:-['Ford', 'BMW']
You can also use the remove() method to remove an element from the array.
cars.remove("Volvo")
print(cars)
Output:-
['Ford', 'BMW']
Note: The list's remove() method only removes the first occurrence of the specified value.
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
fruits.append("orange")
print(fruits)
fruits.clear()
print(fruits)
Output-[]
x = fruits.copy()
Output:-
x = fruits.count("cherry")
print(x)
Output:-1
fruits.extend(cars)
print(fruits)
Output-
x = fruits.index("cherry")
print(x)
Output
fruits.insert(1, "orange")
print(fruits)
Output
fruits.pop(1)
print(fruits)
Output-
['apple', 'cherry']
fruits.remove("banana")
print(fruits)
Output-
['apple', 'cherry']
fruits.reverse()
print(fruits)
Output-
cars.sort()
print(cars)
Output-