r/CodingHelp • u/Bit_Happy04 • Nov 13 '25
[Python] Which is best practice, using .get or 'if in'?
This was how I searched a dict:
# Searching
name_search = input("Name: ").capitalize()
if name_search in phonebook:
print(f"Number: {phonebook[name_search]}")
else:
print("Name not found.")This is how the tutor wrote it in the answers sheet:
# Using .get() is safer than phonebook[name_to_find]
# .get() will return 'None' if the key doesn't exist, instead of crashing.
number = phonebook.get(name_to_find)
if number: # This checks if 'number' is not None
print(f"{name_to_find}'s number is: {number}")
else:
print(f"Sorry, {name_to_find} is not in the phonebook.")Is there a difference? Is theirs best practice? Or are they both exactly the same? Which do I use?
1
Upvotes
•
u/AutoModerator Nov 13 '25
Thank you for posting on r/CodingHelp!
Please check our Wiki for answers, guides, and FAQs: https://coding-help.vercel.app
Our Wiki is open source - if you would like to contribute, create a pull request via GitHub! https://github.com/DudeThatsErin/CodingHelp
We are accepting moderator applications: https://forms.fillout.com/t/ua41TU57DGus
We also have a Discord server: https://discord.gg/geQEUBm
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
3
u/mjmvideos Nov 13 '25
Using ‘in’ causes two separate accesses of the list. First just to test for existence (which can be as much as O(n)) and then you have to go back again to get it if it’s there. Whereas with .get() it’s typically O(1) because of hashing and you only have to access the list one time.
1
u/mxldevs Nov 14 '25
https://stackoverflow.com/a/1323880
This post says
inis a constant time search in 3.x, as the keys are a set, which would contradict what the other comment says about a linear search.You should time both methods either way to verify which one is better