0

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'.

asked Jul 23, 2020 at 3:21
2
  • 1
    odd_numbers = [i for i in number if i%2 !=0] Commented Jul 23, 2020 at 3:23
  • What, exactly, do you mean by the output? Whatever is printed to standard out? Why do you want to do this? You probably should be creating some result instead of merely printing things. Commented Jul 23, 2020 at 3:25

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0
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

1 Comment

"bucket" isn't really standard terminology. This would more commonly be called a "container"

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.