Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to compare element of sublist

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading