I want to remove all the 1's from the sublists so l becomes [[2], [2], [2]] but have trouble keeping track of indices. Can someone help out?

l = [[1, 2, 1],[1, 1, 2],[2, 1, 1]]
i = 0
for element in l:
    while i < len(element):
        if element[i] == 1:
            element.pop(i)
        i += 1
print l

You can go this way

>>> l = [[1, 2, 1],[1, 1, 2],[2, 1, 1]]
>>> for i, element in enumerate(l):
...  l[i] = [x for x in element if x != 1]
... 
>>> l
[[2], [2], [2]]

or even shorter

>>> l = [[1, 2, 1],[1, 1, 2],[2, 1, 1]]
>>> l[:] = ([x for x in e if x != 1] for e in l)
>>> l
[[2], [2], [2]]

You can go this way

>>> l = [[1, 2, 1],[1, 1, 2],[2, 1, 1]]
>>> for i, element in enumerate(l):
...  l[i] = [x for x in element if x != 1]
... 
>>> l
[[2], [2], [2]]

or even shorter

>>> l = [[1, 2, 1],[1, 1, 2],[2, 1, 1]]
>>> l[:] = ([x for x in e if x != 1] for e in l)
>>> l
[[2], [2], [2]]

Can you please write each step individually like in Python 2.x code. A noob like me has tough time understanding code like

l[:] = ([x for x in e if x != 1] for e in l)

Ok, consider this

>>> e = [1, 2, 1, 3, 4, 1, 5]
>>> g = (x for x in e if x != 1)

g is defined by a 'generator expression'. It's a generator object which generates all the elements x from the list e which satisfy x != 1, when you apply the next method:

>>> next(g)
2
>>> next(g)
3
>>> next(g)
4
>>> 
>>> next(g)
5
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

When you put the generator expression in [ ] syntax, it creates a list instead of a generator object. This is called 'list comprehension syntax':

>>> f = [x for x in e if x != 1]
>>> f
[2, 3, 4, 5]

Now the syntax l[:] allows to redefine the elements contained in the list l

>>> l = range(10,15)
>>> l
[10, 11, 12, 13, 14]
>>> l [:] = (x for x in e if x != 1)
>>> l
[2, 3, 4, 5]

I want to remove all the 1's from the sublists so l becomes [[2], [2], [2]] but have trouble keeping track of indices. Can someone help out?

l = [[1, 2, 1],[1, 1, 2],[2, 1, 1]]
i = 0
for element in l:
    while i < len(element):
        if element[i] == 1:
            element.pop(i)
        i += 1
print l

Well, you are almost there. You just have remember that if you pop() the sublist, you effectively advance the index. Modifiy your code like this ...

q = [[1, 2, 1],[1, 1, 2],[2, 1, 1]]

for element in q:
    ix = 0
    while ix < len(element):
        if element[ix] == 1:
            element.pop(ix)
        else:
            ix += 1

print( q )  # [[2], [2], [2]]

Variables i and l are a bitch to read for my sorry eyes, so I changed them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.