0

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.

0

3 Answers 3

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

Comments

1

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

Comments

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

Comments

Your Answer

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.