1
c = int(input('somenumber')) 
p = 0 
while p < c: 
 test = [1, 2] 
 test.append(p) 
 p = p + 1

I want to add numbers to a list but I do not want to use sort (since they are not an arithmetic progression; this is just a test example and I know sort can be used). The above code I tried to do something but the above code literally does nothing (what's wrong with it?

jonrsharpe
123k31 gold badges278 silver badges489 bronze badges
asked Dec 14, 2014 at 10:14
3
  • Note that you keep redefining the list inside the loop. Commented Dec 14, 2014 at 10:19
  • Thanks for the swift reply , I'm trying to add certain numbers to the list which are not necessarily in an AP . like [1, 2, 3 , 4 ...] . In this example I want the out put to be [1, 2, and I have an algorithm that generates those number , I just want to put it in a list . Commented Dec 14, 2014 at 10:19
  • 1
    Yes, but the point stands - you need to initialise the list outside the loop. Commented Dec 14, 2014 at 10:23

2 Answers 2

1

Putting test = [1, 2] inside the loop is going to meant you only get 1,2 and the last p added to the list, you need to initialise the list outside the while loop:

c = int(input('somenumber')) 
p = 0 
test = [1, 2] # outside loop
while p < c: 
 test.append(p)
 p += 1
print(test) # print test to see the contents when the loop finishes
In [1]: for i in range(3):
 ...: test = [] # keeps resetting test to an empty list
 ...: test.append(i)
 ...: print(test,i)
 ...: 
([0], 0)
([1], 1)
([2], 2)
In [2]: test = [] # initialised outside the for loop so we get all elements appended
In [3]: for i in range(3):
 ...: test.append(i)
 ...: print(test,i)
 ...: 
([0], 0)
([0, 1], 1)
([0, 1, 2], 2)
answered Dec 14, 2014 at 10:17
Sign up to request clarification or add additional context in comments.

2 Comments

Ya ! , I got my expected output </br> But I don't get it , what's the difference between putting the list inside the loop and outside the loop ?
you keep making test to equal [1,2] on each iteration, put a print test inside the while loop in your code to see.
0

I think the problem is you are initializing the test list outside the loop.

Anyway starting from your specific example you can get the same result with fewer lines of code:

c = int(input('somenumber'))
p = 0
test = [1, 2]
test.extend(range(p, c))
print (test)
answered Dec 14, 2014 at 10:23

2 Comments

No need for the x for x in... it's redundant. test.extend(range(p, c)) is fine
There's no list comprehension in your current answer.

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.