Python – Check if elements index are equal for list elements


When it is required to check if the index of the elements is equal to the elements in the list, a simple iteration and the enumerate attribute is used.

Example

Below is a demonstration of the same −

my_list_1 = [12, 62, 19, 79, 58, 0, 99]
my_list_2 = [12, 74, 19, 54, 58, 0, 11]

print("The first list is :")
print(my_list_1)

print("The second list is :")
print(my_list_2)

my_list_1.sort()
my_list_2.sort()
print("The first list after sorting is ")
print(my_list_1)

print("The second list after sorting is ")
print(my_list_2)

check_list = [9, 8, 2]
print("The check_list is :")
print(check_list)

my_result = True
for index, element in enumerate(my_list_1):
   if my_list_1[index] != my_list_2[index] and element in check_list:
      my_result = False
      break

print("The result is :")
if(my_result == True):
   print("The index elements is equal to the elements of the list")
else:
   print("The index elements is not equal to the elements of the list")

Output

The first list is :
[12, 62, 19, 79, 58, 0, 99]
The second list is :
[12, 74, 19, 54, 58, 0, 11]
The first list after sorting is
[0, 12, 19, 58, 62, 79, 99]
The second list after sorting is
[0, 11, 12, 19, 54, 58, 74]
The check_list is :
[9, 8, 2]
The result is :
The index elements is equal to the elements of the list

Explanation

  • Two lists of integers are defined and are displayed on the console.

  • They are sorted and displayed on the console.

  • Another list of integers is defined and is displayed on the console.

  • A value is set to Boolean True.

  • The first list is iterated over using enumerate and the index of the first two elements of the two respective lists are compared.

  • If they are equal and if this element is present in the list of integers, the Boolean value is set to False.

  • The control breaks out of the loop.

  • Based on the Boolean value, relevant message is displayed on the console.

Updated on: 13-Sep-2021

503 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements