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?
-
Note that you keep redefining the list inside the loop.jonrsharpe– jonrsharpe2014年12月14日 10:19:12 +00:00Commented 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 .Vrisk– Vrisk2014年12月14日 10:19:37 +00:00Commented Dec 14, 2014 at 10:19
-
1Yes, but the point stands - you need to initialise the list outside the loop.jonrsharpe– jonrsharpe2014年12月14日 10:23:29 +00:00Commented Dec 14, 2014 at 10:23
2 Answers 2
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)
2 Comments
[1,2] on each iteration, put a print test inside the while loop in your code to see.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)
2 Comments
x for x in... it's redundant. test.extend(range(p, c)) is fine