0

suppose message = 1 and contact A in the file and I want to print

1 A
2 B
3 C
4 D

for message in peoplename:
    for contact in contacts_list:
        time.sleep(10)
        print (message, contact)

but it printing like this

1 A
1 B
1 C
1 D
2 A
2 B
2 C
2 D
3 A
3 B
3 C
3 D
4 A
4 B
4 C
4 D

please let me know how to fix it..

user3416720
  • 35
  • 1
  • 5

3 Answers3

2

It looks like you want to match the first item in peoplename with the first item in contacts_list, second with the second etc. You do that using function zip:

for message, contact in zip(peoplename, contacts_list):
    time.sleep(10)
    print (message, contact)
zvone
  • 18,045
  • 3
  • 49
  • 77
1

Try the following using zip:

message = [1,2,3,4]
people = ['A','B','C','D']
for x,y in zip(message,people):
  print(x,y)
#Prints
1 A
2 B
3 C
4 D

You can run Live

Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56
1

You could iterate over the lists' length instead.

length = len(peoplename)
if legnth != len(contacts_list):
    raise ValueError("Lists have different lengths")

for i in range(length):
    time.sleep(10)
    print (peoplename[i], contact_list[i])
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    That does the same thing as `zip`, but uglier... – zvone Jun 10 '18 at 15:27
  • 2
    @ᴀʀᴍᴀɴ What? How could it be more readable to reimplement zip in every place where you need it, instead of using the built-in function which everyone who ever used python understands?! – zvone Jun 10 '18 at 15:30