0

I am reading through Learning Python and just finished the section on lists. While I was playing around to see what I can do with them, I came across something odd:

[2, 3] in [1, 2, 3, 4] == False

You can't test for subsets of lists using the in keyword. Why is this the case?

J Atkin
  • 3,080
  • 2
  • 19
  • 33

7 Answers7

8
[2,3] `is not in` [1,2,3,4]

[2,3] `is in` [1, [2,3] ,4]

2 and 3 are elements in the list but the list [2,3] is not an element in the list.

Dan
  • 383
  • 1
  • 4
6

That is because [2, 3] is in fact not in [1, 2, 3, 4].

To test for subsets, use the issubset function in the sets module.

a = [2, 3]
b = [1, 2, 3, 4]

set(a).issubset(set(b))
ILostMySpoon
  • 2,399
  • 2
  • 19
  • 25
  • Note: `issubset()` is only one possible interpretation. `substr in text` (order, duplicates) is another interpretation e.g., `'bc' in 'abc'`; and `subseq in seq` (order, duplicates are preserved but gaps are possible) e.g., `aad` in `abacd` but `aad` not in `ad`. – jfs Jul 16 '15 at 13:11
3

This is a perfect use of the set object, which contains a issubset method for this exact purpose:

set([2, 3]).issubset([1, 2, 3, 4]) # test if 2 and 3 are located in another iterable
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
3

It's because in checks for element equality. If you had something like

[2, 3] in [[1,2], [2, 3], [3, 4]]

it would work. This works because in looks through the list, compares your element to each of the elements in the list it's looking through, and if any of the comparisons is True, the in statement is True.

You're basically asking why this doesn't return true:

for x in [1, 2, 3, 4]:
    if x == [1,2]:
         return True
Matt Habel
  • 1,493
  • 2
  • 14
  • 35
2

in is for testing list membership, for example, 1 in [1,2,3] is True. If you intend to check subset (order and repetition doesn't matter), you can use the subset operator (looks like less-than-or-equals): {1,2} <= {1,2,3,4,5}

Ming-Tang
  • 17,410
  • 8
  • 38
  • 76
1

This is because 'in' checks if any of the items in the list match your given item.

The items in the list are 1, 2, 3, and 4.

Your item is the list [2, 3], which does not equal any of the above.

Nitesh Patel
  • 631
  • 3
  • 10
1

That's because in both lists, the items are of type int not list.

[1,2,3,4,5] does not include an item of type list i.e [2,3]. Although 2 and 3
are items in [1,2,3,4,5]

[2,3]  in [1, [2,3] ,4] returns true because [2,3] is in [1,[2,3],4,5]

You'll have to test the membership of 2 or 3 in [1,2,3,4,5] separately to return True

 i.e: 2 in [1,2,3,4,5] or 3 in [1,2,3,4,5]
BattleDrum
  • 798
  • 7
  • 13