1

say, i have a string A='baby', want to repeat A 4 times to generate a list looks like this:

['baby', 'baby', 'baby', 'baby']

my current solution is :

((A+".")*4).split('.')[:-1]

however, this looks really awkward.

is there any more civilized solution?

thanks!

James Bond
  • 7,533
  • 19
  • 50
  • 64

3 Answers3

4

Update This answer is expanded with more examples on the canonical question: https://stackoverflow.com/a/24557558/541136

You can do it like this:

['baby'] * 4

Note that this is best only used with immutable items in the list, because they all point to the same place in memory. I use this frequently when I have to build a table with a schema of all strings.

schema = ['string'] * len(columns)

Beware doing this with mutable objects, when you change one of them, they all change because they're all the same object:

foo = [[]] *4
foo[0].append('x')

foo now returns:

[['x'], ['x'], ['x'], ['x']]
Community
  • 1
  • 1
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
0

By using list comprehension:

['baby' for x in range(4)]

Reloader
  • 742
  • 11
  • 22
0

Build a list with single element and multiply the list

['baby']*4
volcano
  • 3,578
  • 21
  • 28