0

I have nested list like that [a,1],[b,2],[c,3]

My code:

for i in list:
    if i[0] == 'b':
        del i

And thats just not working. Code do not crash, but it does not delete neither.

I was trying something like that:

for i in list:
    if something:
        del i[1]
        del i[0]

But it returns [a,1],[],[c,3] and i am not satisfied with that.

c0rv
  • 37
  • 7

3 Answers3

3

It is not a good idea to delete from a list while iterating over it at the same time, try using a list comprehension instead:

List = [L for L in List if L[0] != 'b']
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
2

You can use the enumerate method for that purpose. Take a look at the code snippet below.

li = ['a' , 'b' , 'c' , 'd']
for i , elm in enumerat(li):
    if elm == 'a':
        del li[i]

Using the enumerate function, you'll have access to two values. The first value, i in the code is the index of the element and the second value is the element itself.
You can check the elements in self in each iteration and then use the index to modify the list as needed.

ARK1375
  • 790
  • 3
  • 19
1

The other answer is great, but to answer your question (even if it is not a good practice to delete while iterating):

list = [['a',1],['b',2],['c',3]]
for i in list:
    if i[0] == 'b':
        list.remove(i)
        
print(list)

You could also avoid deleting from the list you're iterating through like this:

list = [['a',1],['b',2],['c',3]]
for i in list.copy():
    if i[0] == 'b':
        list.remove(i)
        
print(list)

The list comprehension in the other example is cleaner and more readable, though.

ᴓᴓᴓ
  • 1,178
  • 1
  • 7
  • 18