J Atkin
J Atkin

Reputation: 3140

Why can't you use 'in' to test if a one list is a subset of another list?

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?

Upvotes: 0

Views: 623

Answers (7)

BattleDrum
BattleDrum

Reputation: 818

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]

Upvotes: 1

ILostMySpoon
ILostMySpoon

Reputation: 2409

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))

Upvotes: 6

Nitesh Patel
Nitesh Patel

Reputation: 631

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.

Upvotes: 1

Matt Habel
Matt Habel

Reputation: 1543

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

Upvotes: 3

Malik Brahimi
Malik Brahimi

Reputation: 16711

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

Upvotes: 3

Ming-Tang
Ming-Tang

Reputation: 17651

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}

Upvotes: 2

Dan
Dan

Reputation: 393

[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.

Upvotes: 8

Related Questions