Some built-in to pad a list in python
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping
--
Chapters
00:00 Question
00:28 Accepted answer (Score 248)
00:52 Answer 2 (Score 45)
01:05 Answer 3 (Score 32)
01:39 Answer 4 (Score 11)
02:19 Thank you
--
Full question
https://stackoverflow.com/questions/3438...
Answer 3 links:
[more-itertools]: https://github.com/erikrose/more-itertoo...
[padded]: https://more-itertools.readthedocs.io/en...
[itertools recipes]: https://docs.python.org/3/library/iterto...
[padnone]: https://more-itertools.readthedocs.io/en...
[take]: https://more-itertools.readthedocs.io/en...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #listmanipulation
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping
--
Chapters
00:00 Question
00:28 Accepted answer (Score 248)
00:52 Answer 2 (Score 45)
01:05 Answer 3 (Score 32)
01:39 Answer 4 (Score 11)
02:19 Thank you
--
Full question
https://stackoverflow.com/questions/3438...
Answer 3 links:
[more-itertools]: https://github.com/erikrose/more-itertoo...
[padded]: https://more-itertools.readthedocs.io/en...
[itertools recipes]: https://docs.python.org/3/library/iterto...
[padnone]: https://more-itertools.readthedocs.io/en...
[take]: https://more-itertools.readthedocs.io/en...
--
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 ) )