DISCOVER
×

How to Multiply All Elements in a List With Python

Updated February 21, 2017

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.

Tip

"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")

Cite this Article A tool to create a citation to reference this article Cite this Article

About the Author

Kevin Walker is a computer programmer who decided to take a few years out from the corporate life and see the world. He spent a total of six years living abroad and teaching English in China, Korea and Mexico before returning to his home in Texas. He uses his programming and teaching experience to write easy-to-understand computer tutorials.