views:

130

answers:

4

I have a list of size < N and I want to pad it up to the size N with a value.

Certainly, I can use something like the following, but I feel that there should be something I missed:

>>> N = 5
>>> a = [1]
>>> map(lambda x, y: y if x is None else x, a, ['']*N)
[1, '', '', '', '']

UPD:

Thank you, all.

I decided to with the solution of @gnibbler. To me it looks the most natural in the absence of a built-in.

+3  A: 
a+=['']*(N-len(a))

or if you don't want to change a in place

new_a = a+['']*(N-len(a))

you can always create a subclass of list and call the method whatever you please

N=5
class MyList(list):
    def ljust(self, n, fillvalue=''):
        return self+[fillvalue]*(N-len(self))

a=MyList(['1'])
b=a.ljust(5, '')
gnibbler
This looks much better, but I still expect something like a _fill_ or _pad_ method or function =)
newtover
I do want to change in place. The former is great. I'll go with that, thank you.
newtover
+1  A: 

gnibbler's answer is nicer, but if you need a builtin, you could use itertools.izip_longest (zip_longest in Py3k):

itertools.izip_longest( xrange( N ), list )

which will return a list of tuples ( i, list[ i ] ) filled-in to None. If you need to get rid of the counter, do something like:

map( itertools.itemgetter( 1 ), itertools.izip_longest( xrange( N ), list ) )
katrielalex
I knew about _izip_longest_ but resulting the code does not look nice =)
newtover
+1  A: 

There is no built-in function for this. But you could compose the built-ins for your task (or anything :p).

(Modified from itertool's padnone and take recipes)

from itertools import chain, repeat, islice

def pad_infinite(iterable, padding=None):
   return chain(iterable, repeat(padding))

def pad(iterable, size, padding=None):
   return islice(pad_infinite(iterable, padding), size)

Usage:

>>> list(pad([1,2,3], 7, ''))
[1, 2, 3, '', '', '', '']
KennyTM
+3  A: 

You could also use a simple generator without any build ins. But I would not pad the list, but let the application logic deal with an empty list.

Anyhow, iterator without buildins

def pad(iterable, padding='.', length=7):
    '''
    >>> iterable = [1,2,3]
    >>> list(pad(iterable))
    [1, 2, 3, '.', '.', '.', '.']
    '''
    for count, i in enumerate(iterable):
        yield i
    while count < length - 1:
        count += 1
        yield padding

if __name__ == '__main__':
    import doctest
    doctest.testmod()
Thierry