In Python, which data structure is more efficient/speedy? Assuming that order is not important to me and I would be checking for duplicates anyway, is a Python set slower than a Python list?
|
It depends on what you are intending to do with it. Sets are significantly faster when it comes to determining if an object is present in the set (as in |
|||||||||
|
|
When you want to store some values which you'll be iterating over, Python's list constructs are slightly faster. However, if you'll be storing (unique) values in order to check for their existence, then sets are significantly faster. It turns out tuples perform in almost exactly the same way as lists, but they do use less memory by removing the ability to modify them after creation (immutable). Iterating
Determine if an object is present
|
|||||||||||||||||
|
|
It depends on what you mean by "checking for duplicates anyway". What percentage of input is unique? Also slower to do what? Try writing (for each of set and list) the code that does what you want to do, and time it. You can then ask here to have your code and timing methodology checked/improved. |
|||
|
|
|
List performance:
Set performance:
You may want to consider Tuples as they're similar to lists but can’t be modified. They take up slightly less memory and are faster to access. They aren’t as flexible but are more efficient than lists. Their normal use is to serve as dictionary keys. Sets are also sequence structures but with two differences from lists and tuples. Although sets do have an order, that order is arbitrary and not under the programmer’s control. The second difference is that the elements in a set must be unique.
|
|||||
|