how to fill a list with 0 using python

Question:

I want to get a fixed length list from another list like:

a = ['a','b','c']
b = [0,0,0,0,0,0,0,0,0,0]

And I want to get a list like this: ['a','b','c',0,0,0,0,0,0,0]. In other words, if len(a) < len(b), i want to fill up list a with values from list b up to length of the list b, somewhat similar to what str.ljust does.

This is my code:

a=['a','b','c']
b = [0 for i in range(5)]
b = [a[i] for i in b if a[i] else i]

print a

But it shows error:

  File "c.py", line 7
    b = [a[i] for i in b if a[i] else i]
                                    ^
SyntaxError: invalid syntax

What can i do?

Asked By: zjm1126

||

Answers:

Can’t you just do:

a = ['a','b','c']
b = [0,0,0,0,0,0,0,0]

c = a + b #= ['a','b','c',0,0,0,0,0,0,0]
Answered By: programmersbook

Why not just:

a = a + [0]*(maxLen - len(a))
Answered By: Achim

Use itertools repeat.

>>> from itertools import repeat
>>> a + list(repeat(0, 6))
['a', 'b', 'c', 0, 0, 0, 0, 0, 0]
Answered By: Iacks

Why not just

c = (a + b)[:len(b)]
Answered By: letitbee

If you want to fill with mutable values, for example with dicts:

map(lambda x: {}, [None] * n)

Where n is the number of elements in the array.

>>> map(lambda x: {}, [None] * 14)
[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
>>> l = map(lambda x: {}, [None] * 14)
>>> l[0]
{}
>>> l[0]['bar'] = 'foo'
>>> l
[{'bar': 'foo'}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]

Populating without the lambda would cause every element to be {'bar': 'foo'}!

Answered By: Talos

To be more explicit, this solution replaces the first elements of b with all of the elements of a regardless of the values in a or b:

a + b[len(a):]

This will also work with:

>>> a = ['a', ['b'], None, False]
>>> b = [0, 1, 2, 3, 4, 5]
>>> a + b[len(a):]
['a', ['b'], None, False, 4, 5] 

If you do not want to the result to be longer than b:

>>> a = ['a', ['b'], None, False]
>>> b = [0, 1, 2]
>>> (a + b[len(a):])[:len(b)]
['a', ['b'], None]
Answered By: dansalmo
LIST_LENGTH = 10
a = ['a','b','c']

while len(a) < LIST_LENGTH:
    a.append(0)
Answered By: litepresence
a+[0]*(len(b) - len(a))

['a', 'b', 'c', 0, 0, 0, 0, 0, 0, 0]
Answered By: johnny

Just another solution:

a = ['a', 'b', 'c']
maxlen = 10
result = [(0 if i+1 > len(a) else a[i])  for i in range(maxlen)]

I like some of the other solutions better.

Answered By: DevPlayer
a = ['a', 'b', 'c']
b = [0, 0, 0, 0, 0, 0]
a.extend(b[len(a):])
# a is now ['a', 'b', 'c', 0, 0, 0]
Answered By: blaze
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.