List comprehension vs map
List comprehension and
map() are both used to create new lists in Python, but they are used in slightly different ways.
List comprehension is a more concise way to create a new list by applying an operation to each element in an existing list. It is written as a single line of code and has the following syntax:
new_list = [expression for item in old_list]
For example, the following code uses list comprehension to create a new list of the squares of the numbers in an existing list:
old_list = [1, 2, 3, 4, 5] new_list = [x**2 for x in old_list] print(new_list) # Output: [1, 4, 9, 16, 25]
map() is a built-in function that takes a function and an iterable as arguments and applies the function to each element of the iterable. It returns a map object, which can be converted to a list using the
list() function. The syntax is:
new_list = list(map(function, iterable))
For example, the following code uses
map() to create a new list of the squares of the numbers in an existing list:
old_list = [1, 2, 3, 4, 5] new_list = list(map(lambda x: x**2, old_list)) print(new_list) # Output: [1, 4, 9, 16, 25]
In most cases list comprehension is more readable, but map can be useful when you want to use a function that you have defined earlier.