1

I have a nested list, for example:

names = [['James', 'Logan', 'Timothy'], ['Ander', 'John', 'Henry']]

and before each name, I would like to add this string 'His name is: ' before each name. So it should print, line by line:

His name is: James
His name is: Logan
His name is: Timothy
His name is: Ander
His name is: John
His name is: Henry

I used

for n in names: print(f'His name is: {n}')

but that didn't give me the output I was looking for. Can you please help me figure out how to do this?

jarvis
  • 39
  • 4
  • 3
    Welcome to SO. Please read [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822) - especially the "Make a good faith attempt to solve the problem yourself first." part – Mike Scotty Sep 27 '21 at 15:39
  • 3
    You'll probably want to look at [Flatten a list of lists](https://stackoverflow.com/q/2158395/5763413), the use of [f-strings](https://realpython.com/python-f-strings/), and [`for` loops](https://wiki.python.org/moin/ForLoop). – blackbrandt Sep 27 '21 at 15:39
  • 1
    The problem statement is not clear to me. Do you want to actually mutate the list or do you want to prepend that string only during printing/display? – Matias Cicero Sep 27 '21 at 15:40
  • I used this at first, but didn't give me what I was looking for: ' for n in names: print(f'His name is: {n}') ' – jarvis Sep 27 '21 at 15:45
  • One list, one loop, as in your original question an hour ago… Now you have two nested lists and would need two nested loops… – deceze Sep 27 '21 at 15:47

3 Answers3

2
from itertools import chain


for name in chain.from_iterable(names):
    print(f'His name is: {name}')
Amin
  • 2,605
  • 2
  • 7
  • 15
2

You have a nested list. So, use nested for loop -

names = [['James', 'Logan', 'Timothy'], ['Ander', 'John', 'Henry']]

for i in names:
    for n in i:
        print(f'His name is: {n}')
PCM
  • 2,881
  • 2
  • 8
  • 30
2

If you want to avoid using a nested loop or itertools you can just combine all the nested lists using sum:

names = [['James', 'Logan', 'Timothy'], ['Ander', 'John', 'Henry']]

for name in sum(names, []):
    print(f'His name is: {name}')
Jab
  • 26,853
  • 21
  • 75
  • 114