FAQ: Learn Python: Python Lists and Dictionaries - Remove a Few Things

faq

#1

This community-built FAQ covers the “Remove a Few Thing” exercise in Codecademy’s lessons on Python.

FAQs for the Codecademy Python exercise Remove a Few Thing:

Join the Discussion. We Want to Hear From You!

Have a new question or can answer someone else’s? Reply (reply) to an existing thread!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources about Python in general? Go here!

Want to take the conversation in a totally different direction? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account, billing, Pro, or Pro Intensive? Reach out to our support team!

None of the above? Find out where to ask other questions here!


#2

What is the difference between deleting something and removing it?

Edit: thx for the great and fast responses :smiley:


#3

Generally, when we delete something we are removing references to that object.

>>> c = 42
>>> print (c)
42
>>> del(c)
>>> print (c)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    print (c)
NameError: name 'c' is not defined
>>> 

In the case of a list element, we would be removing the reference to that index…

>>> a = [1,2,3,4,5]
>>> del(a[4])
>>> a[4]
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    a[4]
IndexError: list index out of range
>>> a
[1, 2, 3, 4]
>>> 

Note that if the item is not at the end of the list, the reference still exists at that index, but with the values to the right shifted to fill the gap. The last index reference will be gone.

>>> del(a[1])
>>> a
[1, 3, 4]
>>> del(a[1])
>>> a[1]
4
>>> 

In the case of dictionaries, we would be removing the reference to the key-value pair…

>>> b = { 'one': 1, 'two': 2, 'three': 3 }
>>> b
{'three': 3, 'one': 1, 'two': 2}
>>> del(b['two'])
>>> b['two']
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    b['two']
KeyError: 'two'
>>> b
{'three': 3, 'one': 1}
>>> 

We can delete a element from a set…

>>> s = {5, 8, 13, 21}
>>> del(a[1])
>>> a
[1, 3, 4]
>>> 

Like lists, the last index is gone.

Tuples are immutable so we cannot delete elements.

>>> t = (3, 6, 9, 12)
>>> del(t[0])
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    del(t[0])
TypeError: 'tuple' object doesn't support item deletion
>>> 

We can, however, delete a tuple (as with any other object)…

>>> del(t)
>>> t
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    t
NameError: name 't' is not defined
>>> del(s)
>>> s
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    s
NameError: name 's' is not defined
>>> del(b)
>>> b
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    b
NameError: name 'b' is not defined
>>> del(a)
>>> a
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    a
NameError: name 'a' is not defined
>>> 

Since functions are also objects, this means we can delete them, too…

>>> def foo():
	return "Foo"

>>> foo()
'Foo'
>>> del(foo)
>>> foo()
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    foo()
NameError: name 'foo' is not defined
>>> 

From the above we can see that del() is a far-reaching function of the standard library that is not tied to any one or more classes. This can lead to errors if not implemented carefully, and for this reason should be the last thing reached for. Better that we use the class methods, when they are available. This is where object.remove() comes into play.

>>> a = [1,2,3,4,5]
>>> a.remove(4)
>>> a
[1, 2, 3, 5]
>>> a = [1,2,3,4,5] + [1,2,3,4,5]
>>> a.remove(4)
>>> a
[1, 2, 3, 5, 1, 2, 3, 4, 5]
>>> 

Note that only the first occurrence of 4 is removed. To remove all the occurrences, we need to write a while loop…

>>> a = [1,2,3,4,5] + [1,2,3,4,5]
>>> while 4 in a:
	a.remove(4)

	
>>> a
[1, 2, 3, 5, 1, 2, 3, 5]
>>> 

To remove multiple adjacent elements in a list we turn back to del()

>>> del(a[3:6])
>>> a
[1, 2, 3, 3, 5]
>>> 

Care must be taken when writing code of this nature.

Dictionaries (dict objects) do not have a remove method.

>>> b = { 'one': 1, 'two': 2, 'three': 3 }
>>> b.remove('one')
Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    b.remove('one')
AttributeError: 'dict' object has no attribute 'remove'
>>> 

Sets do have a remove method…

>>> s = {5, 8, 13, 21}
>>> s.remove(8)
>>> s
{13, 5, 21}
>>> 

It goes without saying that tuples do not.

Lists, dictionaries and sets also have a pop() method which lets us capture the removed item for further use. That will come up, if it hasn’t already.

>>> c = b.pop('two')
>>> c
2
>>> b
{'three': 3, 'one': 1}
>>> 

#4

Can’t delete objects, only names

I’d say there’s no difference between delete and remove. They are synonyms. (English words with no special different meanings in programming)

If something happens to have a method named remove, then one would have to read its documentation to figure out what that means.

If something implements the del operator then its key refers to the same value as for the [] operator


#5

Ah, I stand corrected. Thanks.

Can you clarify with an example, please?


#6

del and [] use the same addressing (not enforced by python)

[] is get and set by key, del is remove by key

[] has the dunder names: __setitem__ and __getitem__, del has __delitem__

It’s not a 1:1 mapping exactly, python might use those dunder names for other things than those operators, and those operators might get their behaviours from elsewhere (for example if it’s implemented in C)


#7

Great example, and more food for thought.


#8

Is there a way to remove an item from a list in using its index via list.remove () ? else by what other way ?


#9

In Python there is the list.pop(N) method, where N is the index of the value we wish to remove.

Bear in mind that when we remove an element, all the elements to the right, shift left so their indices will have all changed (and the list gotten shorter).

.pop(0)   =>  removes first element
.pop()    =>  removes last element
.pop(-1)  =>  also removes last element
.pop(N)   =>  removes Nth element (N is in range)

#10

Thanks

Le dim. 17 févr. 2019 à 20:44, Roy via Codecademy Forums codecademy@discoursemail.com a écrit :