TransWikia.com

Basic problems in python

Stack Overflow Asked by Ujjwal on December 5, 2021

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

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 by Gray_Rhino on December 5, 2021

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 by Kevin Mayo on December 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP