186

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 every 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?

Andras Deak
  • 27,857
  • 8
  • 66
  • 96
user1188821
  • 1,901
  • 2
  • 12
  • 6

4 Answers4

207

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]]
>>>
RanRag
  • 43,987
  • 34
  • 102
  • 155
18

Here is the solution I was looking for. If you would like to create List2 that contains the difference of the number elements in List1.

list1 = [12, 15, 22, 54, 21, 68, 9, 73, 81, 34, 45]
list2 = []
for i in range(1, len(list1)):
  change = list1[i] - list1[i-1]
  list2.append(change)

Note that while len(list1) is 11 (elements), len(list2) will only be 10 elements because we are starting our for loop from element with index 1 in list1 not from element with index 0 in list1

Kean Amaral
  • 3,227
  • 2
  • 12
  • 8
17

You may as well use for x in values rather than for x in values[:]; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3...

The code only prints one item per value of x - and x is iterating over the elements of values, which are the sublists. So it will only print each sublist once.

comex
  • 229
  • 1
  • 2
  • 3
  • 4
    values[:] slices out all the elements of values, right? I'm assuming that you meant the temporary list created from the slicing. Just want to make sure. – batbrat Feb 04 '12 at 03:30
  • 1
    Thanks for mentioning the unwanted copy. @batbrat it doesn't slices out, it slices off, what I mean is that the values are duplicated, and still in `values`. – AsTeR Jan 15 '19 at 15:22
  • Thanks for clarifying. – batbrat Jan 21 '19 at 13:27
3

Do this instead:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)
ldz
  • 2,172
  • 14
  • 20