Python: How to combine the results of for loop into one output?

11,408

Solution 1

Use a list comprehension:

[num*2 for num in numbers]

>>> numbers = [1, 2, 3]
>>> [num*2 for num in numbers]
[2, 4, 6]
>>> 

Solution 2

Create new List type variable result and add values into it by list append() method.

Demo:

>>> numbers = [1, 2, 3]
>>> result = []
>>> for i in numbers:
...   result.append(i*2)
... 
>>> result
[2, 4, 6]
>>> 
Share:
11,408
juiceb0xxie
Author by

juiceb0xxie

Updated on June 27, 2022

Comments

  • juiceb0xxie
    juiceb0xxie almost 2 years
    numbers = [1, 2, 3]
    
    for number in numbers:
       number = number * 2 
    
    #For the output I will get:
    2
    4
    6
    

    How do I modify my code so the results can be combined (eg. [2, 4, 6]) without using the print statement?

    • wallyk
      wallyk about 9 years
      Do you mean you do not want to output the result? Only calculate it?
    • abarnert
      abarnert about 9 years
      I don't know what you mean "# For the output I will get: 2 4 6". There is no output here at all. And no effect; all you're doing each time through the loop is reassigning the loop variable number to a different value, which you then immediately forget.
    • TigerhawkT3
      TigerhawkT3 about 9 years
      It sounds like you're confusing the Python interpreter's behavior of displaying returned values with the built-in print() function.