+ 2
How to remove consecutive elements from a list?
Sample data: [(), (), (''”,), ('a', 'b'), ('a', 'b', 'c'), ('d')] Expected output: [('a', 'b'), ('a', 'b', 'c'), 'd'] I want to remove empty tuples from this list , this is my code- for i in Sampledata: if i: continue else: Sampledata.remove(i) but it fails to remove the second element .. how to fix ? this is output- [(), ('',), ('a', 'b'), ('a', 'b', 'c'), 'd']
4 odpowiedzi
+ 6
You could've asked for "How to remove empty elements from a list?". I mean what if the elements you wanted to remove were not in consecutive order?
From what I've learned, removing item(s) from an iterable while iterating though it is not a good idea. Because the size of the iterable may change during iteration, next item fetched may not be the one that was intended.
The second element (as per original post) contains slanted quotes, it triggered error and prevented the code from running. The slanted quotes had to be removed first.
Considering all list's elements were tuples, we need to validate whether the tuple's element(s) were truthy. Checking whether the tuple was non empty is not enough, we need to also check whether any of the tuple's element(s) were valid.
The last element ( 'd' ) is not a tuple, it's a string. Put a comma in to make it a tuple ( 'd', )
https://code.sololearn.com/ceJ0Et753REw/?ref=app
+ 5
https://code.sololearn.com/cPYsw5hO1qnR/?ref=app
+ 4
l = [(), (), ("",), ('a', 'b'), ('a', 'b', 'c'), ('d',)]
l2 = [i for i in l if len(i)>=1 and i[0]!='']
print(l2)
0
Try to use the 'while' condition instead of 'for'.