– Operations on lists 1 | slices, deletion – Operations on lists 1 | slices, deletion

As we’ve said before, omitting both start and end makes a copy of the whole list:

The snippet’s output is: [10, 8, 6, 4, 2].

The previously described del instruction is able to delete more than just a list’s element at once – it can delete slices too:

Note: in this case, the slice doesn’t produce any new list!

The snippet’s output is: [10, 4, 2].

Deleting all the elements at once is possible too:

The list becomes empty, and the output is: [].

Removing the slice from the code changes its meaning dramatically.

Take a look:

The del instruction will delete the list itself, not its content.

The print() function invocation from the last line of the code will then cause a runtime error:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
NameError: name 'my_list' is not defined

Fonte: https://edube.org/study/pe1

Sandbox: https://edube.org/sandbox

Lascia un commento

Il tuo indirizzo email non sarà pubblicato.

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.

%d blogger hanno fatto clic su Mi Piace per questo: