0

I'm new to python!

players = ["Matt","Joe", "Barry","Billy"]
numbers = [1,2,3,4]

def assignment(players, numbers):
    for i in players:
        for j in numbers:
            print i,j
assignment(players,numbers)

My attempt is above.

I want to try make the answer =

Matt 1
Joe 2
Barry 3
Billy 4 

but at the minute each name is being assigned each number! Any advice on how to fix this?

Phil
  • 47
  • 9

2 Answers2

1

use zip

players = ["Matt","Joe", "Barry","Billy"]
numbers = [1,2,3,4]

for a in zip(players, numbers):
    print(*a)

In the case where your lists are not the same length zip would only pair items that have a corresponding index in the other list, if you want the other items you can use itertools.zip_longest in python3 and specify a fillvalue for python to fill in the items that are empty, for Example:

from itertools import zip_longest

players = ["Matt","Joe", "Barry","Billy", "Johnson", "Riyad"]
numbers = [1,2,3,4]

for a in zip_longest(players, numbers, fillvalue=0):
    print(*a)

Output

Matt 1
Joe 2
Barry 3
Billy 4
Johnson 0
Riyad 0
danidee
  • 9,298
  • 2
  • 35
  • 55
1
def assignment(players, numbers):
    for i, j in zip(players, numbers):
        print i,j
ForceBru
  • 43,482
  • 10
  • 63
  • 98