0

i want to add a word for ex. 100 times to a list, here is my code

my expected result is ['word', 'word', 'word'...]

i = 1

text = [ ]

while i <= 100:

  text += 'word'

  i += 1


print(text)

the output is -> 'w', 'o', 'r', 'd', 'w', 'o', 'r', 'd', 'w', 'o', 'r', 'd', 'w', 'o', 'r', 'd', 'w', ...

all the letters are added separately,

Can smbdy explain why? And what is the right code for adding 100 words to a list ?

Thank you

tobias_k
  • 81,265
  • 12
  • 120
  • 179
Tigran
  • 19
  • 4
  • 5
    try `text += ["word"]` or `text.append("word")`, or just `text = ["word"] * 100` – tobias_k Mar 03 '21 at 14:54
  • You have a misunderstanding of what `+=` does to a string and a list – marcusshep Mar 03 '21 at 14:55
  • [`+=` operation for a list is equivalent to `.extend`](https://stackoverflow.com/a/66304392/2823755) - it *adds* each item in the right-hand-side to the list. Strings are iterable and the operation sees each character as an item. – wwii Mar 03 '21 at 15:10

3 Answers3

1

You want to use text.append(word) or text += ['word'] instead. When adding items to a list, += is effectively the same as .extend.

Since strings can be iterated on, it's adding each character into the list individually

Wondercricket
  • 7,651
  • 2
  • 39
  • 58
0

Use extend.

text = ['existing', 'words']
text.extend(['word']*100)

print(text)
norie
  • 9,609
  • 2
  • 11
  • 18
0
mul=100
text = ['existing', 'words']
# repeat the text n-times
m_text=[[x]*mul for x in text]
# flattened list
flat_list = [item for sublist in m_text for item in sublist]
mpx
  • 3,081
  • 2
  • 26
  • 56