2

I have two lists which have unknown number of elements. One list containing names and another castes

'''Like This'''

names = ['name1','name2',........'name99'] 
castes = ['cast1','cast2',........'cast99']

And i want print like this:

Hello Name1 cast1.
Hello Name2 Cast2.
.
.
.
.
.
Hello Name99 Cast99

I have tried this but it doesnot work.

for i in names:
   for j in castes:
      print('Hello '+ i + j)

But it prints randomly. like...

Hello Name1 Cast1
Hello Name1 Cast2
.
.
Hello Name1 Cast99
.
.
.
Hello Name2 Cast1
Hello Name2 Cast2
.
.
Hello Name3 Cast99
.
.
.
Austin
  • 25,759
  • 4
  • 25
  • 48

2 Answers2

5

The zip() builtin will do what you want, combining lists that have corresponding elements.

>>> names = 'n1 n2 n3 n4'.split()
>>> castes = 'c1 c2 c3 c4'.split()
>>> pprint.pprint(list(zip(names, castes)), width=20)
[('n1', 'c1'),
 ('n2', 'c2'),
 ('n3', 'c3'),
 ('n4', 'c4')]

From there you can finesse each tuple as you wish:

for name, caste in zip(names, castes):
    print('Hello', name.title(), caste.title())

This works for as many attributes as you care to specify:

names = 'n1 n2 n3 n4'.split()
castes = 'c1 c2 c3 c4'.split()
towns = 't1 t2 t3 t4'.split()
for name, caste, town in zip(names, castes, towns):
    print(f'{name} ({caste}) lives in {town}.')
J_H
  • 17,926
  • 4
  • 24
  • 44
3

Use zip() to iterate over two lists simultaneously:

names = ['name1','name2','name99'] 
castes = ['cast1','cast2','cast99']

for x, y in zip(names, castes):
    print(f'Hello {x} {y}')

# Hello name1 cast1
# Hello name2 cast2                                        
# Hello name99 cast99

This can be done without zip() with just one loop. Problem with your approach is you used one loop inside other so the inner one repeats as many times as the outer specifies.

for i in range(len(names)):
    print(f'Hello {names[i]} {castes[i]}')
Austin
  • 25,759
  • 4
  • 25
  • 48