mehmettekn
mehmettekn

Reputation: 21

What is an easier way to iterate over nested lists in python?

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

Answers (6)

Matthias
Matthias

Reputation: 13222

Let me just add this one.

print(1 in zip(*nested_list)[1])

Upvotes: 0

arshajii
arshajii

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

John La Rooy
John La Rooy

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

Gareth Latty
Gareth Latty

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

Chris Greenough
Chris Greenough

Reputation: 116

Something like this?

for (x,y) in nested_list:print y

Upvotes: 0

Joran Beasley
Joran Beasley

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

Related Questions