John Lapoya
John Lapoya

Reputation: 592

Some error in double for, python

I have some variables like this:

letters = ["a","b","c","d"]
num = ["1","2","3","4"]
names = ["Paul","John"]

for i in letters:
    for j in names:
          output= names[j] + letters[i] + num[i]
          print output

I would like to get some kind of output like this:

output print:
"Paul a 1" 
"John a 1" 
"Paul b 2" 
"John b 2" 
"Paul c 3"
"John c 3" 
"Paul d 4" 
"John d 4" 

But somehow I cant find the right way to get this combination. Any ideas where is the error?

Upvotes: 1

Views: 146

Answers (1)

sshashank124
sshashank124

Reputation: 32189

You should do it as this instead:

letters = ["a", "b", "c", "d"]
num = ["1", "2", "3", "4"]
names = ["Paul", "John"]

for a, i in enumerate(letters):
    for j in names:
          print j, i, num[a]

The problem you are facing is that i, and j are elements of the list not indices. If you want to get the index and element from a list, you use enumerate().

Example

>>> a = ['a', 'b', 'c']

>>> for i, item in enumerate(a):
...     print i, item
...
0 a
1 b
2 c

Upvotes: 4

Related Questions