0

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!

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.