Lesson 27 of 55
8 mins readPython Key Management: exists vs defined & delete
In Plain English
`exists $hash{key}` tests if a key has been declared in the hash (even if its value is `undef`). `delete $hash{key}` removes the key-value pair completely.
Deep Dive: How It Works
exists: Returns true if the key is present in the hash table.
defined: Returns true if the key is present AND its value is not undef.
delete: Removes the key from the hash table and returns the removed value.
Core Rules to Remember

exists vs defined: A key can exist with an `undef` value; `exists` checks key presence.

delete: Removes the key from the hash completely.
Live Interactive Example
Hit Run Code to see it liveTesting Existence and Deletion
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Output Console
Click "Run Code" to view the rendered output.
How it works: Timeout exists even though its value is undef. Retries was removed by delete.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Delete Hash Key
Declare `%cache = ( token1 => "abc", token2 => "xyz" );`
Call `delete $cache{token1};`
Print `"Remaining keys: " . join(", ", keys %cache) . "\n"`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.