Python Lambda
❮ PreviousNext ❯
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
ExampleGet your own Python Server
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
Try it Yourself »
Lambda functions can take any number of arguments:
Example
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
Try it Yourself »
Example
Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Try it Yourself »
ADVERTISEMENT
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
Use that function definition to make a function that always doubles the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Try it Yourself »
Or, use the same function definition to make a function that always triples the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Try it Yourself »
Or, use the same function definition to make both functions, in the same program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Try it Yourself »
Use lambda functions when an anonymous function is required for a short period of time.
Python Arrays
❮ PreviousNext ❯
Note: Python does not have built-in support for Arrays, but Python Lists can be
used instead.
Arrays
Note: This page shows you how to use LISTS as ARRAYS, however, to work with
arrays in Python you will have to import a library, like the NumPy library.
Arrays are used to store multiple values in one single variable:
ExampleGet your own Python Server
Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]
Try it Yourself »
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Access the Elements of an Array
You refer to an array element by referring to the index number.
Example
Get the value of the first array item:
x = cars[0]
Try it Yourself »
Example
Modify the value of the first array item:
cars[0] = "Toyota"
Try it Yourself »
The Length of an Array
Use the len() method to return the length of an array (the number of elements
in an array).
Example
Return the number of elements in the cars array:
x = len(cars)
Try it Yourself »
Note: The length of an array is always one more than the highest array index.
Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
Example
Print each item in the cars array:
for x in cars:
print(x)
Try it Yourself »
Adding Array Elements
You can use the append() method to add an element to an array.
Example
Add one more element to the cars array:
cars.append("Honda")
Try it Yourself »
Removing Array Elements
You can use the pop() method to remove an element from the array.
Example
Delete the second element of the cars array:
cars.pop(1)
Try it Yourself »
You can also use the remove() method to remove an element from the array.
Example
Delete the element that has the value "Volvo":
cars.remove("Volvo")
Try it Yourself »
Note: The list's remove() method only removes the first occurrence of the
specified value.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Python List append() Method
❮ List Methods
ExampleGet your own Python Server
Add an element to the fruits list:
fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
Try it Yourself »
Definition and Usage
The append() method appends an element to the end of the list.
Syntax
list.append(elmnt)
Parameter Values
Parameter Description
elmnt Required. An element of any type (string, number, object etc.)
More Examples
Example
Add a list to a list:
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)
Python List clear() Method
❮ List Methods
ExampleGet your own Python Server
Remove all elements from the fruits list:
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
Try it Yourself »
Definition and Usage
The clear() method removes all the elements from a list.
Syntax
list.clear()
Parameter Values
No parameters
❮ List Methods
Python List copy() Method
❮ List Methods
ExampleGet your own Python Server
Copy the fruits list:
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
Try it Yourself »
Definition and Usage
The copy() method returns a copy of the specified list.
Syntax
list.copy()
Parameter Values
No parameters
Python List count() Method
❮ List Methods
ExampleGet your own Python Server
Return the number of times the value "cherry" appears in the fruits list:
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
Try it Yourself »
Definition and Usage
The count() method returns the number of elements with the specified value.
Syntax
list.count(value)
Parameter Values
Parameter Description
value Required. Any type (string, number, list, tuple, etc.). The value to searc
More Examples
Example
Return the number of times the value 9 appears int the list:
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
Try it Yourself »
❮ List Methods
Python List extend() Method
❮ List Methods
ExampleGet your own Python Server
Add the elements of cars to the fruits list:
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
Try it Yourself »
Definition and Usage
The extend() method adds the specified list elements (or any iterable) to the
end of the current list.
Syntax
list.extend(iterable)
Parameter Values
Parameter Description
iterable Required. Any iterable (list, set, tuple, etc.)
More Examples
Example
Add a tuple to the fruits list:
fruits = ['apple', 'banana', 'cherry']
points = (1, 4, 5, 9)
fruits.extend(points)
Try it Yourself »
❮ List Methods
Python List index() Method
❮ List Methods
ExampleGet your own Python Server
What is the position of the value "cherry":
fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
Try it Yourself »
Definition and Usage
The index() method returns the position at the first occurrence of the specified
value.
Syntax
list.index(elmnt)
Parameter Values
Parameter Description
elmnt Required. Any type (string, number, list, etc.). The element to search fo
More Examples
Example
What is the position of the value 32:
fruits = [4, 55, 64, 32, 16, 32]
x = fruits.index(32)
Try it Yourself »
Note: The index() method only returns the first occurrence of the value.
❮ List Methods
Python List insert() Method
❮ List Methods
ExampleGet your own Python Server
Insert the value "orange" as the second element of the fruit list:
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
Try it Yourself »
Definition and Usage
The insert() method inserts the specified value at the specified position.
Syntax
list.insert(pos, elmnt)
Parameter Values
Parameter Description
pos Required. A number specifying in which position to insert the value
elmnt Required. An element of any type (string, number, object etc.)
❮ List Methods
Python List pop() Method
❮ List Methods
ExampleGet your own Python Server
Remove the second element of the fruit list:
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
Try it Yourself »
Definition and Usage
The pop() method removes the element at the specified position.
Syntax
list.pop(pos)
Parameter Values
Parameter Description
pos Optional. A number specifying the position of the element you want to
default value is -1, which returns the last item
More Examples
Example
Return the removed element:
fruits = ['apple', 'banana', 'cherry']
x = fruits.pop(1)
Try it Yourself »
Note: The pop() method returns removed value.
Python List remove() Method
❮ List Methods
ExampleGet your own Python Server
Remove the "banana" element of the fruit list:
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
Try it Yourself »
Definition and Usage
The remove() method removes the first occurrence of the element with the
specified value.
Syntax
list.remove(elmnt)
Parameter Values
Parameter Description
elmnt Required. Any type (string, number, list etc.) The element you want to
Python List reverse() Method
❮ List Methods
ExampleGet your own Python Server
Reverse the order of the fruit list:
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
Try it Yourself »
Definition and Usage
The reverse() method reverses the sorting order of the elements.
Syntax
list.reverse()
Parameter Values
No parameters
Related Pages
The built-in function reversed() returns a reversed iterator object.
❮ List Methods
Python List sort() Method
❮ List Methods
ExampleGet your own Python Server
Sort the list alphabetically:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
Try it Yourself »
Definition and Usage
The sort() method sorts the list ascending by default.
You can also make a function to decide the sorting criteria(s).
Syntax
list.sort(reverse=True|False, key=myFunc)
Parameter Values
Parameter Description
reverse Optional. reverse=True will sort the list descending. Default is reverse=
key Optional. A function to specify the sorting criteria(s)
More Examples
Example
Sort the list descending:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
Try it Yourself »
Example
Sort the list by the length of the values:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
Try it Yourself »
Example
Sort a list of dictionaries based on the "year" value of the dictionaries:
# A function that returns the 'year' value:
def myFunc(e):
return e['year']
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]
cars.sort(key=myFunc)
Try it Yourself »
Example
Sort the list by the length of the values and reversed:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)
Try it Yourself »
❮ List Methods