tchenatny
tchenatny

Reputation: 3

how to create a list after a while loop

I have a question about how to create a list after the while loop. I want to put all the numbers I get from while loop into a list for example:

x=4
while(1):
    print(x)
    x=x+1
    if x==8:break

then I get

4
5
6
7

I want to show these numbers in one list.

Upvotes: 0

Views: 154

Answers (3)

John Kugelman
John Kugelman

Reputation: 361615

l=[]
x=4

while(1):
    print(x)
    l.append(x)

    x=x+1
    if x==8:break

print(l)

That's how you'd add it to your code. FYI, if you want to do it the "Pythonic" way, it's as simple as:

l = range(4, 8)

Upvotes: 2

JMillner
JMillner

Reputation: 49

You are looking for the append() function. Check out the python lists document here for more information.

list=[] #declare a blank list to use later
x=4

while(1):
    list.append(x) #add x to the list
    x += 1 # a shorthand way to add 1 to x
    if x == 8:break

print(list) #after the loop is finished, print the list

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 113955

L = []
i = 4
while i<=8:
    print(i)
    L.append(i)
    i += 1

Upvotes: 1

Related Questions