A list is a container data type that represents a collection of ordered elements in which each element has an index relative to other elements in the list. Each element can be accessed directly through its index.
Sometimes we may want to perform an action to each element of a list. For example you may want to transform a list of strings so that all the strings are in uppercase.
There are various ways that we can achieve this efficiently:
- Using the builtin map() function.
- Using list comprehension.
- Using for loops.
Using the map() function
The builtin map()
function conveniently applies a function to each elements of an iterable. We can use it with a list to perform an action to each element of the list.
map(func, mylist)
func |
The function to be applied to the list elements. |
mylist |
The list. |
The function should take only one required argument, which is the element in the list that is being processed by the function. The map()
function returns an iterator that yields the result of applying the function for each item in the list.
#a list of strings
mylist = ['python', 'java', 'c++', 'ruby']
#transform all the list elements to uppercase
transformed = list(map(str.upper, mylist))
print(transformed)
In the above example:
- We defined a list of strings
- We called the map() function with the str.upper() as the function argument and our list as the second argument.
- The map function returns an iterator that yields the uppercased elements.
- We used the builtin
list()
function to create a new list from the elements yielded by the iterator.
#a list of lists
mylist = [[1, 3, 2], [7, 9, 8], [6, 5, 4]]
#sort each inner list
transformed = list(map(sorted, mylist))
print(transformed)
In the above example we used the map()
function to sort each of the inner lists. We passed the buitin sorted()
function as the function argument, the outcome is that each of the returned iterator yields sorted lists.
Let us now use a custom function rather than the builtin methods and functions.
#a list of integers
mylist = [12, 10, 13, 7, 19]
#subtract 5 from each list integer
transformed = list(map(lambda x: x - 5, mylist))
print(transformed)
In the above example, we passed a lambda function as the func
argument , the function when applied to the list, subtracts 5 from each integer in the list.
Using list comprehension
List comprehension is a convenient syntax that combines the features of looping, conditional execution and sequence building all into one concise syntax.
transformed = [<expression> for <item> in <mylist>]
In the <expression
> part we can use a function with the current item as the argument. The resulting list will contain the results of applying the function to each element of the original list.
#a list of strings
mylist = ['1', '2', '3', '4', '5']
#transform all the strings to integers
transformed = [int(i) for i in mylist]
print(transformed)
In the above example:
- We defined a list of strings where each string is a valid integer literal.
- We used the buitin
int(i)
as the expression part of the syntax. The i represents the current list element during each iteration. The builtin int() function transforms an input object into its integer equivalent. - The resulting list contains all the elements of the original list with each string transformed to its integer form.
#a list of strings
mylist = ['india', 'japan', 'canada', 'kenya']
#capitalize each string in the list
transformed = [i.capitalize() for i in mylist]
print(transformed)
In the above example, during each iteration we call the capitalize()
method of the current element. The capitalize()
method returns the current string but with its first character in uppercase form.
Using for loops
One of the most obvious way to apply a function to list elements is by using the for loops. The fact that lists are mutable also makes it possible to use assignment to replace the current element in the original list so that the transformation happens in-place. This is in contrary to the previous methods that results in creation of a new list.
mylist = ['kigali', 'delhi', 'beijing', 'ottawa']
for i, v in enumerate(mylist):
mylist[i] = v.upper()
print(mylist)
The builtin enumerate() function returns an iterator object that yields a a tuple containing the current element's index and the value during each iteration. We used it above to keep track of the current element's index and then used the index to replace the original element with the transformed value to the list.
#a list of lists
mylist = [[4, 2, 3], [5, 7, 6], [30, 25, 20]]
#sort the inner lists
for lst in mylist:
lst.sort()
print(mylist)
In the above example, we called the sort()
method of each inner list. We did not need to reassign because sorting with the sort()
method affects the original list.