Looping over a list in Python

PythonList

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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]]
>>>

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

Do this instead:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1188821View Question on Stackoverflow
Solution 1 - PythonRanRagView Answer on Stackoverflow
Solution 2 - PythoncomexView Answer on Stackoverflow
Solution 3 - PythonKean AmaralView Answer on Stackoverflow
Solution 4 - PythonAaditya ShahView Answer on Stackoverflow