Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the __lt__ actually doing for lists [duplicate]

Say I have two lists, and I run the following command

>>> s = [1, 2, 3]
>>> t = [1, 2, 4]
>>> s > t
False
>>> s < t
True

But if I were to run the following command

>>> s = [1, 2, 3]
>>> t = [1, 1, 4]
>>> s > t
True
>>> s < t
False

Have to admit, I'm not too familiar with the PY3 codebase. What exactly is going on in the __lt__, __le__, __gt__, __ge__, __ne__, __eq__ methods?

like image 956
mortonjt Avatar asked May 17 '16 22:05

mortonjt


People also ask

What is the __ LT __ method?

__lt__ is a special method for less than operator(<). Usually, we are using less than operator to check the less than numbers. Already we learned about the less-than operator in the topic of The Secret of Comparators | Comparision Operators In Python.

What does __ LT __ return?

Python – __lt__ magic method Python __lt__ magic method is one magic method that is used to define or implement the functionality of the less than operator “<” , it returns a boolean value according to the condition i.e. it returns true if a<b where a and b are the objects of the class.

Does list () Create a new list?

The list() constructor returns a list. If iterable is passed as a parameter, it creates a list consisting of iterable's items.

Can you use += to add to a list Python?

This article describes how to add to a list in Python. You can add an item (element) to a list with append() and insert() , and add another list to a list with extend() , + , += , and slice.


2 Answers

The comparison is lexicographical. If you read the definition of that, you will understand everything.

Iterate the pairs of elements in order, and the first non-equal pair determines the winner of the ordering.

like image 144
wim Avatar answered Oct 08 '22 02:10

wim


It's comparing them naively, i.e. element by element. 4 > 3, but 2 > 1.

like image 42
Ignacio Vazquez-Abrams Avatar answered Oct 08 '22 04:10

Ignacio Vazquez-Abrams