Richard K Yu
Richard K Yu

Reputation: 2202

How to avoid double-counting index of duplicate element in list comprehension

Suppose I have a list:

nums = [3,3,1,5,6]

I want to use list comprehension to iterate through this list with two variables and report the index of the variables while looping through. I have the following code below.

indices = [print(nums.index(x),nums.index(y)) for x in nums for y in nums]

The problem I encounter is the output:

0 0
0 0
0 2
0 3
0 4
0 0
0 0
0 2
0 3
0 4
2 0
2 0
2 2
2 3
2 4
3 0
3 0
3 2
3 3
3 4
4 0
4 0
4 2
4 3

As you will note, the index "1" is never printed because the nums.index(x) will only report the first instance of the element it has found, rather than the location of the element itself.

How do I can I have the results print accurately? As an example of the desired output, I made all values unique and reran the code.

0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
2 4
3 0
3 1
3 2
3 3
3 4
4 0
4 1
4 2
4 3
4 4

Upvotes: 0

Views: 427

Answers (1)

Chris
Chris

Reputation: 16147

You're looking for enumerate, which will give you the index position as a variable as you iterate through.

nums = [3,3,1,5,6]
indices = [print(i,z) for i,x in enumerate(nums) for z,y in enumerate(nums)]

Upvotes: 2

Related Questions