bfaskiplar
bfaskiplar

Reputation: 885

for loop to extend a list to a particular length

I want the below piece of code to append 2's to the list 'a' until it gets the size of ten. However, it doesn't work in the way I wish. What am I missing?

a = [1,2]

for ctr in range(0,len(a)):
    print ctr
    if len(a) < 10:
        a.append(2)

Upvotes: 3

Views: 1705

Answers (4)

Jon Clements
Jon Clements

Reputation: 142226

Just to throw in another approach for completeness... (and may be more flexible about padding out values from other iterables etc...)

>>> from itertools import chain, islice, repeat
>>> list(islice(chain(a, repeat(2)), 10))
[1, 2, 2, 2, 2, 2, 2, 2, 2, 2]

Upvotes: 1

kindall
kindall

Reputation: 184375

range(len(a)) is evaluated once, when the loop begins. At this point, your list has two items, so the loop will be executed exactly twice.

To do what you want, a better approach would be:

a += [2] * (10 - len(a))

You know how many items you wish to add, so add them all at once, rather than adding them one at a time in a loop.

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1124548

You only loop twice; the len(a) is only evaluated to create the range(), not on every iteration of the loop. Thus, you only end up with a list of length 4.

Use a while statement instead:

while len(a) < 10:
    a.append(2)

or .extend() with the correct number of 2s:

a.extend([2] * (10 - len(a)))

or use += (which is short-hand for .extend()):

a += [2] * (10 - len(a))

Both of these approaches avoid loops altogether.

Upvotes: 4

jdi
jdi

Reputation: 92637

Just do a while loop until its the size you want:

a = [1,2]
while len(a) < 10:
    a.append(2)

The problem is that you were basing your original loop on the current size of a. When it evaluates, it will only loop 2 times. A while loop on the other hand is going to keep evaluating that length each time.

Upvotes: 2

Related Questions