How to Multiply All Elements in a List With Python


One of the nice features common to many of the latest programming languages like Python is support for lambda functions and functional programming techniques. In Python, this is implemented with the "map" method, a powerful method that takes a function and a list, performs the function individually on every element in the list and returns the result. What once would have been a tedious for-loop is now a one-liner.

  • Open a terminal. In Windows by clicking "Start" followed by "Run" and then typing "cmd." In Mac OS X, click "Spotlight" and type "Terminal."

  • Type "python" into the terminal.

  • Type the following line to define a list:

    list = [1,2,3,4,5,6,7,8,9,10]

  • Type the following line to multiply every element in the list by two:

    map(lambda x: x * 2, list)

    The "map" function performs a function on every element of a list. The "lambda" command defines a new, unnamed and temporary function for use in the map command and nowhere else. Combined, you can quickly create a new "times two" function and call it on every element in the list automatically.

Tips & Warnings

  • "Map" does not require a lambda function. Any valid Python function can be passed into "map." For example, try this to get all the ASCII values of a block of English text: map(ord, "Kevin")


Promoted By Zergnet


You May Also Like

  • What Is Lambda Max?

    Lambda max is the wavelength at which the maximum fraction of light is absorbed by a solution. Lambda (λ) is a Greek...

  • List of Values for Kids

    Children begin picking up behavioral cues from their parents and others at a very early age. Whether those behaviors are positive or...

Related Searches

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!