Looping over a list in Python


Question

I have a list with sublists in it. I want to print all the sublists with length equal to 3.

I am doing the following in python:

for x in values[:]:
    if len(x)==3:
        print x

values is the original list. Does the above code print all the sublist with length equal to 3 for each value of x? I want to display the sublists where length==3 only once.

The problem is solved. The problem is with the Eclipse editor. I don't understand the reason, but it is displaying only half of my list when I run my loop.

Are there any settings I have to change in Eclipse?

1
161
5/27/2018 8:46:27 PM

Try this,

x in mylist is better and more readable than x in mylist[:] and your len(x) should be equal to 3.

>>> mylist = [[1,2,3],[4,5,6,7],[8,9,10]]
>>> for x in mylist:
...      if len(x)==3:
...        print x
...
[1, 2, 3]
[8, 9, 10]

or if you need more pythonic use list-comprehensions

>>> [x for x in mylist if len(x)==3]
[[1, 2, 3], [8, 9, 10]]
>>>
178
2/4/2012 3:21:52 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon