Reputation: 21
Suppose I have a list like the one below and I am trying to iterate over nested_list[i][1]
elements and return a boolean
nested_list = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [1, 8], [1, 9]]
print 1 in (nested_list[i][1] for i in range(nested_list))
I am still a newbie in Python, so someone with more experience tell me please: is there a more Pythonic way to do this?
Upvotes: 2
Views: 2515
Reputation: 129497
Try this:
print 1 in (i[1] for i in nested_list)
If you only want to check for membership, I would suggest that you do indeed use (...)
instead of [...]
because the latter would create the entire list when there is really no need to do so.
Upvotes: 4
Reputation: 304137
This answer using itertools will shortcircuit at the first hit too.
>>> from operator import itemgetter
>>> from itertools import imap
>>>
>>> 1 in (imap(itemgetter(1), nested_list))
True
Upvotes: 0
Reputation: 88977
A.R.S has already suggested a good solution, but an alternative answer is simply any(i[1] == 1 for i in nested_list)
.
Upvotes: 2
Reputation: 113940
>>> import numpy
>>> a = numpy.array(nested_list)
>>> a[:,1]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> 1 in a[:,1]
True
Upvotes: 0