Tech With Tim Logo
Go back

Map() Function

Map Function

The map function can be used to apply a function to every element in a given list. For example, if we wanted to apply a function f1 to a list of numbers we would usually do something like this:

def f1(x):
    return x + x/2

nums = [1,5,6,7,2]

newList = []
for item in nums:
    numList.append(f1(nums))

However the map function can eleminate a lot of this work and perform this same task in one line.

def f1(x):
    return x + x/2

nums = [1,5,6,7,2]

newList = list(map(f1, nums))

#This will create a new list where each element at index i is f1(nums[i])
Design & Development by Ibezio Logo