Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

3. Map Function

Sumit Rawal answered on May 13, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers

  • map python 3
  • how the map function works javascript
  • Javascript Map properties and methods
  • map function
  • .map method
  • map in python 3
  • map function
  • map function
  • The complete map() method syntax
  • Map operations
  • map function
  • function with .map javascript

  • 3. Map Function

    0

    Map is a built-in function that takes a function and an iterable as arguments and applies the function to each element in the iterable.

    map(function, iterable)

    An iterable could be an object which can be iterated, such as — a list, tuple, etc.

    The map function can be used to replace loops that are used to perform some operation on each element in a list. Here’s an example:

    Example 1: Finding the square of numbers

    ## Traditional Loop

    nums = (1, 3, 4, 5, 6, 7)

    def square_numbers(nums):

    squares = []

    for num in nums:

    squares.append(num**2)

    ## One-liner

    squares = list(map(lambda x: x**2, nums))

    Example 2: Consider the scenario where we have a list of sentences and want to count the number of words in each sentence. We can use a multi-line loop to achieve this as follows:

    ## Traditional Loop

    sentences = ['This is the first sentence.',

    'And this is the second sentence.',

    'Finally, the third sentence.']

    word_counts = []

    for sentence in sentences:

    words = sentence.split()

    word_count = len(words)

    word_counts.append(word_count)

    ### line liner

    word_counts = list(map(lambda sentence: len(sentence.split()), sentences)) 

    Popularity 1/10 Helpfulness 1/10 Language whatever
    Source: Grepper
    Link to this answer
    Share Copy Link
    Contributed on May 13 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.