Python – Check if elements in a specific index are equal for list elements


When it is required to check if the elements in a specific index are equal to another list of elements, a simple iteration and a Boolean value are used.

Example

Below is a demonstration of the same −

my_list_1 = [69, 96, 23, 57, 13, 75, 13]
my_list_2 = [68, 21, 69, 23, 49, 35, 73]

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

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

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

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

check_list = [66, 89, 69]
print("The second list is : " )
print(check_list)

print("The check list after sorting is :")
check_list.sort()
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

if(my_result == True):
   print("The elements of the list are equal to the elements in the check list")
else:
   print("The elements of the list aren't equal to elements in the check list")

Output

The first list is :
[69, 96, 23, 57, 13, 75, 13]
The first list after sorting is :
[13, 13, 23, 57, 69, 75, 96]
The second list is :
[68, 21, 69, 23, 49, 35, 73]
The first list after sorting is :
[21, 23, 35, 49, 68, 69, 73]
The second list is :
[66, 89, 69]
The check list after sorting is :
[66, 69, 89]
The elements of the list aren't equal to elements in the check list

Explanation

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

  • They are sorted and displayed on the console.

  • A Boolean value is assigned to True.

  • The first list is iterated over using ‘enumerate’.

  • The elements at specific indices are compared and the element is checked to be found in the third list.

  • If it is not found, the Boolean value is assigned to ‘False’.

  • The control breaks out of the loop.

  • Depending on the Boolean value, the message is displayed on the console.

Updated on: 13-Sep-2021

592 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements