Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to save all element index after removing element in python

sentence = [[1,0,3],[2,0,0],[0,0,5]]
empty = []
for element in sentence :
    for icelement in element :
        if not icelement == 0:
            empty.append(icelement)
        
         
        
print(empty)
print(empty[2]) #this should give 3 or empty[8] should give 5

I did many attempt but stil having problem. I know this is because python automatically updating the elements index but dont know how to control it. Any suggestion will help me.

num = [1,0,4,5]
print(num[3]) #gives 5
for n in num :
    if n == 0:
        num.remove(n)

print(num[3])# doesnt exist.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You want to preserve the position in the original flattened list while removing some elements?

The options are either flatten the list, leave the zeroes in place; just ignore them.

empty = [item for sublist in sentence for item in sublist] #[1, 0, 3, 2, 0, 0, 0, 0, 5]
print(empty[2]) # returns 3

Or do something with a dictionary, use the original position in the flattened list as the key.

count = 0
empty = {}
for element in sentence :
    for icelement in element :
        if not icelement == 0:
            empty[count] = icelement
        count +=1

print(empty[2]) # returns 3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading