5 способов проверить, одинаковы ли два списка в Python

Чтобы проверить, совпадают ли два списка в Python, вы можете использовать различные методы. Вот несколько подходов:

  1. Метод 1. Сравните списки напрямую с помощью оператора ==.

    list1 = [1, 2, 3]
    list2 = [1, 2, 3]
    
    if list1 == list2:
       print("The lists are the same.")
    else:
       print("The lists are different.")
  2. Метод 2. Преобразуйте списки в наборы и сравните их.

    list1 = [1, 2, 3]
    list2 = [3, 2, 1]
    
    if set(list1) == set(list2):
       print("The lists are the same.")
    else:
       print("The lists are different.")
  3. Метод 3: используйте функцию all()с пониманием списка.

    list1 = [1, 2, 3]
    list2 = [1, 2, 3]
    
    if all(x == y for x, y in zip(list1, list2)):
       print("The lists are the same.")
    else:
       print("The lists are different.")
  4. Метод 4. Сравните длину списков и проверьте каждый элемент.

    list1 = [1, 2, 3]
    list2 = [1, 2, 3]
    
    if len(list1) == len(list2) and all(x == y for x, y in zip(list1, list2)):
       print("The lists are the same.")
    else:
       print("The lists are different.")
  5. Метод 5: используйте функцию numpy.array_equal(), если у вас установлен numpy.

    import numpy as np
    
    list1 = [1, 2, 3]
    list2 = [1, 2, 3]
    
    if np.array_equal(list1, list2):
       print("The lists are the same.")
    else:
       print("The lists are different.")