Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output from <= in python is weird

Tags:

python

list

set

>>> [6,7,8,16,18] <= [6,8,11,13,17]
True

<= Should return True if every element in left set is in right set. But 7,16,18 are not in the right list. Even if I put the numbers in sets like so

>>> (6,7,8,16,18) <= (6,8,11,13,17)
True

https://docs.python.org/2/library/sets.html

like image 250
kevin Avatar asked Dec 01 '25 01:12

kevin


1 Answers

You are using lists and tuples, not sets. Use {...} for set literals:

>>> {6, 7, 8, 16, 18} <= {6, 8, 11, 13, 17}
False

or use set([...]) or frozenset([...]). Set literal syntax is only available in Python 2.7 and 3.x.

Lists and tuples don't support set operations. Instead, <, <=, > and >= comparisons follow lexicographical ordering conventions; the contents are compaired pairwise and the outcome is based on the first value that differs between the two sequences.

Lexicographically sorted, your left-hand list sorts before the right-hand (6 == 6, then 7 < 8) so the outcome for sequences is entirely correct.

like image 122
Martijn Pieters Avatar answered Dec 03 '25 15:12

Martijn Pieters