0

Is there a way to print out 2 lists together, for one I can do for

for g in grades:
    print(g)

Which results in: 83, 25, 90 etc.. I have a second list called 'cc'. Both lists have the same number of items in the proper order. I'm trying to print them as

print(cc[0])
print(g[0])

And so on for all the items in the list.

I've already tried

for g in grades:
    for x in cc:
        print(x)
        print(g)

Which as expected prints out many more times than once for each. Is there a way to properly do this? I think I'm writing this clear enough.

martineau
  • 119,623
  • 25
  • 170
  • 301
Aaron
  • 33
  • 1
  • 3
  • 10

2 Answers2

3

Since the two lists have the same length, you can use zip.

zip creates a tuple of the successive items in each sequence. g, x "unpacks" this tuple; that is assign the respective values to g and x.

for x, g in zip(cc, grades):
    print(x, g, end='\n')
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
0

You can use index function:

list1 = ['a','b','c']
list2 = [0,1,2]

for i in list1:
    print(i)
    print(list2[list1.index(i)])

Updated (thanks for @juanpa.arrivillaga):

But it's a bad solution because it has quadratic-time algorithm. It's better to use enumerate:

for index, item in enumerate(list1):
    print(item)
    print(list2[index])
Andrzej S.
  • 472
  • 3
  • 19