简体   繁体   中英

List with empty indexes in python, how to remove?

I am trying to remove a position from an empty list, as a simple example that demonstrates or is trying to remove.

#Test about fruits

fruits = []

fruits.append('maça')
fruits.append('goiaba')
fruits.append('uva')
fruits.append('pera')
fruits.append('bananna')
fruits[1] = []

print (fruits)

Output : ['maça', [], 'uva', 'pera', 'bananna']

Desired output ['maça', 'uva', 'pera', 'bananna']

Just remembering that it is a simple example, so I can apply it in a more robust program that I am developing that presents the same problem of having a "position" in the list with a 'null' or empty value in this case.

Use pop() to remove an element from a list by its index, rather than assigning an empty value to the index.

fruits.pop(1)

or del

del fruits[1]

pop() allows you to retrieve the value being removed at the same time.

You can use

del fruits[1]

See Difference between del, remove and pop on lists for the differences.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM