Trying to compare element of sublist

Advertisements

I am trying to check if the particular element of list inside list are equal or not:
I am having list inside list and in that I want to check the 3 element i.e at index 2 of the every sublist are equal or not.
Here is my code i have tried:


a = [['File1', 0, ' Message to check whether all this are same or not'], ['File1', 1, ' Message to check whether all this are same or not'], ['File1', 2, ' Message to check whether all this are same or not'], ['File1', 3, ' Message to check whether all this are same or not'], ['File1', 4, ' Message to check whether all this are same or not']]

for index,word1 in enumerate(a):
        for index2,word2 in enumerate(a):
            if index!=index2:
                if index[2] == index2[2]:
                    print(True)

When I run the above code I got the TypeError:

if index[2] == index2[2]:
TypeError: 'int' object is not subscriptable

Please help me to sort out my problem

I want True If the 3rd element of all sublist are equal

>Solution :

It can be done in an elegant manner


a = [['File1', 0, ' Message to check whether all this are same or not'], ['File1', 1, ' Message to check whether all this are same or not'], ['File1', 2, ' Message to check whether all this are same or not'], ['File1', 3, ' Message to check whether all this are same or not'], ['File1', 4, ' Message to check whether all this are same or not']]


# pick the 3rd elem of the first sub list
key_item = a[0][2]

# iterate over the rest of the sub lists
for sub_list in a[1:]:
    if sub_list[2] != key_item:
        print('False')
        break
else:
    print('True')

The else block just after for/while is executed only when the loop is
NOT terminated by a break statement.

Leave a ReplyCancel reply