Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for 'in' operator for nested lists

If I want to find something in a list in python I can use the 'in' operator:

list = ['foo', 'bar']
'foo' in list #returns True

But what should I do if I want to find something in a nested list?

list = [('foo', 'bar'), ('bar', 'foo')]
'foo' in list #returns False

Is it possible to do it in one row without a for loop for example?

Thanks!

like image 866
Eknoes Avatar asked Feb 24 '13 22:02

Eknoes


People also ask

Can a list be nested in another list?

As we know, that list can contain any object, so here the concept of nested list is introduced. So simply, when there is a list containing a list inside itself as an element(sublist) or data, then that list is known as a nested list. To get more clear with the nested list refer to an example given below.

Can you have lists inside of lists Python?

Lists are useful data structures commonly used in Python programming. A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if you want to create a matrix or need to store a sublist along with other data types.

Which operator can be used with list?

Lists are mutable, meaning their elements can be changed unlike string or tuple. We can use the assignment operator = to change an item or a range of items. We can add one item to a list using the append() method or add several items using the extend() method. We can also use + operator to combine two lists.


2 Answers

You probably want any:

>>> list = [('foo', 'bar'), ('bar', 'foo')]
>>> any('foo' in e for e in list)
True

Some sort of loop is inevitable though.

like image 57
Pavel Anossov Avatar answered Sep 18 '22 21:09

Pavel Anossov


You could use itertools.chain like that :

from itertools import chain

nested__seq = [(1,2,3), (4,5,6)]

print 4 in chain(*nested__seq)

PS : you shouldn't override bultins like "list"

like image 20
dugres Avatar answered Sep 19 '22 21:09

dugres