1

I'm trying to print the element with the index of every element in the list

But my implement prints every element with index 0 and every element with index 1 until the last index

can anyone fix it, I'm stuck here?

if __name__=="__main__":

    r = [6, 5, 3, 3]
    diff = [[(i,j)for i in r]for j in range(5)]
    print(diff)

Actual output:

[[(6, 0), (5, 0), (3, 0), (3, 0)], [(6, 1), (5, 1), (3, 1), (3, 1)], [(6, 2), (5, 2), (3, 2), (3, 2)], [(6, 3), (5, 3), (3, 3), (3, 3)], [(6, 4), (5, 4), (3, 4), (3, 4)]]

Desired output:

[(6, 0),(5, 1),(3, 2),(3, 3)]

Matt Ball
  • 332,322
  • 92
  • 617
  • 683
Joe
  • 223
  • 1
  • 9

3 Answers3

2

Try enumerate:

diff = [(i, j) for j, i in enumerate(r)]

A less preferrable way would be to use zip:

diff = list(zip(r, range(len(r))))
VHarisop
  • 2,685
  • 1
  • 11
  • 24
1

You are looking for enumerate , which gives you the element with index like this:

>>> r = [6, 5, 3, 3]
>>> output = [(val, indx) for indx, val in enumerate(r)]
>>> output
[(6, 0), (5, 1), (3, 2), (3, 3)]

a simple way to understand enumerate:

diff = [(r[i], i) for i in range(len(r))]
dnit13
  • 2,377
  • 14
  • 31
1

I think you're asking for the functionality provided by enumerate() (getting both the value and index of an iterable)

r = [6, 5, 3, 3]
print([(val, i) for i, val in enumerate(r)])
jDo
  • 3,670
  • 1
  • 8
  • 28