user15075009
user15075009

Reputation: 1

How to get particular element from list of tuples

I have this list of tuples:

l1 = [(1, 8), (6, 8), (8, 7), (2, 6)]

I want to compare 1st element of each tuple with 1st element of next tuple How can I access the next tuple's 1st element?

Since operating lists is a bit easier than tuples, I first made this as list of list as follows:

l1 = [[1, 8], [6, 8], [8, 7], [2, 6]]

and then tried this:

for i in l1:
    if l1[i][1] == l1[i+1][1]:
...

but l1[i+1][1] doesn't work what am I doing wrong in (i+1) code

Upvotes: 0

Views: 45

Answers (2)

Damien Castaignede
Damien Castaignede

Reputation: 53

Try to use range with the length of your list -1 :

for i in range(len(l1) - 1) :
    if l1[i][0] == l1[i+1][0]:
         ...

with this you won't get indexError when reaching your last member of the list.

Upvotes: 2

Bijesh Raj Kunwar
Bijesh Raj Kunwar

Reputation: 63

While comparing adjacent elements when traversing through the elements always make sure your stopping condition is the second last element.

Also if you are comparing the first element your indexing should start at 0 and not 1.

for i in range(len(l1)-1):
    if l1[i][0] == l1[i+1][0]:

Upvotes: 0

Related Questions