How can you store output of any piece of code into a new variable?
number=range(20)
for number in number:
if number%2!=0:
print(number)
Like I want to store the output of this in a new variable called 'odd_numbers'.
2 Answers 2
Use a list comprehension:
number = range(20)
odd_numbers = [i for i in number if i%2]
Or append them:
number = range(20)
odd_numbers = []
for i in number:
if i % 2:
odd_numbers.append(i)
answered Jul 23, 2020 at 3:27
Kevin Mayo
1,1591 gold badge8 silver badges19 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
odd_numbers = []
for i in range(20):
if i%2 != 0:
odd_number.append(i)
Any time you want to store something you should create bucket and put values into that bucket (variable, list, dict, set).
answered Jul 23, 2020 at 3:29
Gray_Rhino
1,3331 gold badge15 silver badges31 bronze badges
1 Comment
juanpa.arrivillaga
"bucket" isn't really standard terminology. This would more commonly be called a "container"
lang-py
odd_numbers = [i for i in number if i%2 !=0]