Looping over a list in Python
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?
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]]
>>>
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.
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
Do this instead:
values = [[1,2,3],[4,5]]
for x in values:
if len(x) == 3:
print(x)