0

I've just started playing around with python lists, I've written the simple code below expecting the printed file to display the numbers [12,14,16,18,20,22] but only 22 is displayed. Any help would be great.

a=10
b=14
while a <= 20:
    a=a+2
    b=b-1
    datapoints=[]
    datapoints.insert(0,a)
print datapoints
5
  • 6
    Well, you are setting datapoints to an empty list in the loop. I suggest you move the datapoints=[] line to take place outside of the loop. Commented Oct 19, 2016 at 14:19
  • 3
    Also, use list.append() if you expected numbers to be added at the end, which your expected output suggests you want. Commented Oct 19, 2016 at 14:20
  • 3
    Does b have a purpose? Commented Oct 19, 2016 at 14:22
  • Or if you want to prepend the numbers, use collections.deque so you can call appendleft and perform the prepend efficiently (lists only have efficient appends on the right, prepending is O(n)). Commented Oct 19, 2016 at 14:23
  • 1
    while is often not that pythonic IMO for a case like this, consider using a for loop instead in combination with range Commented Oct 19, 2016 at 14:28

3 Answers 3

1
a=10
b=14
datapoints=[]  # this needs to be established outside of your loop

while a <= 20:
    a=a+2
    b=b-1
    datapoints.append(a)
print datapoints

You need to set up datapoints outside your loop, and then inside your loop, append each additional datum to datapoints

Sign up to request clarification or add additional context in comments.

1 Comment

cheers, I'm new to this and sometimes its hard to see the wood for the trees.
1

Joel already answered but if you want a more compact code you can use range

numbers = []
for number in range(12,24,2):
    # do whatever you want with b
    numbers.append(number)

print numbers

or if you only want to print the numbers you can do

print [number for number in range(12,24,2)]

Comments

0

you can achieve the expected list as output by using the range() method. It takes three parameters, start, stop and step.

data_points = range(12, 23, 2)  # range returns list in python 2
print data_points

Note that, in python 3 the range() is a sequence-type. So, you will have to cast it to list in python 3

data_points = list(range(12, 23, 2))  # python 3
print(data_points) 

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.