Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

how to multiply,divide,add and subtract from every member of a list

If I had a list such as: my_list = [1,2,3] how do I multiply every member in the list by 2 so that the new list would be [2,4,6]

2 Answers

Steven Parker
Steven Parker
243,656 Points

There's several ways to do this — for one, you could simply use a loop:

new_list = []
for i in my_list:
    new_list.append(i*2)

But there's a function called "map" that's perfectly suited for this kind of task:

new_list = list(map(lambda x: x*2, my_list))
Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points
# don't forget about using list comprehension
>>> my_list = [1,2,3]
>>> new_list = [x*2 for x in my_list]
>>> new_list
[2, 4, 6]

# to change *in-place*
>>> for idx in range(len(my_list)):
...     my_list[idx] *= 2
...
>>> my_list
[2, 4, 6]