How do I multiply each element in a list by a number?

后端 未结 8 1212
囚心锁ツ
囚心锁ツ 2020-11-27 04:29

I have a list:

my_list = [1, 2, 3, 4, 5]

How can I multiply each element in my_list by 5? The output should be:



        
8条回答
  •  孤街浪徒
    2020-11-27 04:58

    Since I think you are new with Python, lets do the long way, iterate thru your list using for loop and multiply and append each element to a new list.

    using for loop

    lst = [5, 20 ,15]
    product = []
    for i in lst:
        product.append(i*5)
    print product
    

    using list comprehension, this is also same as using for-loop but more 'pythonic'

    lst = [5, 20 ,15]
    
    prod = [i * 5 for i in lst]
    print prod
    

提交回复
热议问题