Some built-in to pad a list in python
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island
--
Chapters
00:00 Some Built-In To Pad A List In Python
00:23 Accepted Answer Score 271
00:41 Answer 2 Score 9
01:07 Answer 3 Score 34
01:31 Answer 4 Score 53
01:38 Thank you
--
Full question
https://stackoverflow.com/questions/3438...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #listmanipulation
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island
--
Chapters
00:00 Some Built-In To Pad A List In Python
00:23 Accepted Answer Score 271
00:41 Answer 2 Score 9
01:07 Answer 3 Score 34
01:31 Answer 4 Score 53
01:38 Thank you
--
Full question
https://stackoverflow.com/questions/3438...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #listmanipulation
#avk47
ACCEPTED ANSWER
Score 271
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
class MyList(list):
def ljust(self, n, fillvalue=''):
return self + [fillvalue] * (n - len(self))
a = MyList(['1'])
b = a.ljust(5, '')
ANSWER 2
Score 53
I think this approach is more visual and pythonic.
a = (a + N * [''])[:N]
ANSWER 3
Score 34
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, '', '', '', '']
ANSWER 4
Score 9
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 ) )