Martin
Martin

Reputation: 41

How to add string to end of list of lists of string

I have a list like the following:

list1 = [['Dog', 'Cat', 'Chicken'], ['Cow', 'Pig', 'Sheep'], ['Lizard', 'Fish', 'Goat']]

I would like to add a string, i.e. "Hi", to each element in each list within list1.

So that it would be the following:

list1 = [['DogHi', 'CatHi', 'ChickenHi'], ['CowHi', 'PigHi', 'SheepHi'], ['LizardHi', 'FishHi', 'GoatHi']]

I have tried this simple code but the output is just the initial list.

for sublist in list1:
   for each_word in sublist:
       each_word = each_word + "Hi"

Any advice would be appreciated, I am sure the solution is trivial. Thanks!

Upvotes: 0

Views: 306

Answers (1)

quamrana
quamrana

Reputation: 39374

Strings in python are immutable, so you will have to make a new string and put it back into the list:

for sublist in list1:
   for index,each_word in enumerate(sublist):
       sublist[index] = each_word + "Hi"

Upvotes: 1

Related Questions