0

I have a larger list that I want to assign or otherwise take action on by elements of a smaller list, but do so only once. For example:

emailList = ['tom@gmail.com', 'dick@gmail.com', 'harry@gmail.com', 'jane@gmail.com']
fileList = ['file_1.zip', 'file_2.zip']

I want to alternately assign the elements of fileList to the elements of emailList. So:

tom@gmail.com -> file_1.zip
dick@gmail.com -> file_2.zip
harry@gmail.com -> file_1.zip
jane@gmail.com -> file_2.zip

I have this...half working (for simplicity's sake, I'm just using print statements to represent action):

    for email in emailList:
        for file in zippedList:
            print(email + "will receive " + file)
            zippedList.pop(0)

Yields:

    Email: tom@gmail.com
    will receive Contest_Packet_1.zip
    Email: dick@gmail.com
    will receive Contest_Packet_2.zip

Of course the propblem is that once zippedList is empty, it ends, and no further assignments are made. However, when I do NOT pop the elements of the smaller list, then the elements of the larger list each both get both of the elements in the smaller list assigned or otherwise actioned. It yields this:

    Email: tom@gmail.com
    will receive Contest_Packet_1.zip
    Email: tom@gmail.com
    will receive Contest_Packet_2.zip
    Email: dick@regula.one
    will receive Contest_Packet_1.zip
    Email: dick@regula.one
    will receive Contest_Packet_2.zip
    Email: harry@gmail.com
    will receive Contest_Packet_1.zip
    Email: harry@gmail.com
    will receive Contest_Packet_2.zip
    Email: jane@gmail.com
    will receive Contest_Packet_1.zip
    Email: jane@gmail.com
    will receive Contest_Packet_2.zip

Surely there's an easier way to do this. Thoughts?

deleteno5
  • 29
  • 3

1 Answers1

1

Probably the easiest way is to just assign the value based on if the index of the current iteration is even or not. You can use enumerate() for that. The code below assigns the current list index to the index variable, and the current email to the email variable. Now just step through and assign the values one after another to the list:

emailList = ['tom@gmail.com', 'dick@gmail.com', 'harry@gmail.com', 'jane@gmail.com']
fileList = ['file_1.zip', 'file_2.zip']

for index, email in enumerate(emailList):
      if index %2 ==0 : # Even numbers
            print(f"Email: {email}, File: {fileList[0]}")
      else: # odd numbers
            print(f"Email: {email}, File: {fileList[1]}")
Kieran Wood
  • 1,297
  • 8
  • 15