When should I use a dictionary, list or set?
Are there scenarios that are more suited for each data type?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A
listkeeps order,dictandsetdon’t: when you care about order, therefore, you must uselist(if your choice of containers is limited to these three, of course 😉 ).dictassociates each key with a value, whilelistandsetjust contain values: very different use cases, obviously.setrequires items to be hashable,listdoesn’t: if you have non-hashable items, therefore, you cannot usesetand must instead uselist.setforbids duplicates,listdoes not: also a crucial distinction. (A "multiset", which maps duplicates into a different count for items present more than once, can be found incollections.Counter— you could build one as adict, if for some weird reason you couldn’t importcollections, or, in pre-2.7 Python as acollections.defaultdict(int), using the items as keys and the associated value as the count).Checking for membership of a value in a
set(ordict, for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list’s length in the average and worst cases. So, if you have hashable items, don’t care either way about order or duplicates, and want speedy membership checking,setis better thanlist.