Sumod
Sumod

Reputation: 3846

Evaluating subset of a list using in operator

I have following test code.

a = ['a', 'b', 'c', 'd', 'e']
c = a * 3
b = a

but b in c returns False. b is a sub sequence of c and the list c contains b. So why is it returning false?

Thanks in advance.

Upvotes: 1

Views: 346

Answers (2)

Chaos Manor
Chaos Manor

Reputation: 1220

If you had this code:

a = ['a', 'b', 'c', 'd', 'e']
c = [a] * 3
b = a

when you type b in c you would get True.

In this case

c = [a] * 3 (with [ ] around a)

would return:

[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

Upvotes: 0

Ratzkewatzke
Ratzkewatzke

Reputation: 288

b in c

Does not work because b looks like:

['a', 'b', 'c', 'd', 'e']

and c looks like:

['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

In other words, b is not an element of the sequence. Instead, b is a subsequence. If you were to construct c as follows:

c = [a, a, a]

Then c would look like:

[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

And "b in c" would return True.

Hope this helps.

Upvotes: 5

Related Questions