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!
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.
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With