Sobes.tech
Junior

Provide examples of using the map function in Python.

sobes.tech AI

Answer from AI

The map(function, iterable, ...) function applies a function to all items of an iterable and returns an iterator with the results.

Examples:

  1. Applying a function to each element of a list:

    # Squares each number
    numbers = [1, 2, 3, 4, 5]
    squared_numbers = list(map(lambda x: x**2, numbers))
    # Result: [1, 4, 9, 16, 25]
    
  2. Applying a function to elements of multiple iterables:

    # Adds corresponding elements of two lists
    list1 = [1, 2, 3]
    list2 = [4, 5, 6]
    sum_list = list(map(lambda x, y: x + y, list1, list2))
    # Result: [5, 7, 9]
    
  3. Converting strings to numbers:

    # Converts list of strings to integers
    str_numbers = ['10', '20', '30']
    int_numbers = list(map(int, str_numbers))
    # Result: [10, 20, 30]
    
  4. Applying string methods:

    # Converts all strings to uppercase
    words = ['apple', 'banana', 'cherry']
    uppercase_words = list(map(str.upper, words))
    # Result: ['APPLE', 'BANANA', 'CHERRY']
    
  5. Using with a custom function:

    # Custom function
    def process_item(item):
        return item * 2 + 1
    
    data = [10, 20, 30]
    processed_data = list(map(process_item, data))
    # Result: [21, 41, 61]