There are a lot of container data types that available in python. But there is one particularly popular container, it is list. Its flexibility causes a lot of Python programmers love to use it. It can hold various data type such as integers, strings and custom class instances. Moreover, it’s mutable, which allows us to add or remove items as applicable. But sometimes Melbourne Web Developers and python programmers use it too often and forget that there are viable alternatives.
In this article, we would like to highlight three scenarios where there are better options than lists that should be considered.
- Membership Checking
When building an application or website, you often need to check if the data container has the specific item that you’re looking for. Certainly, lists have the needed built-in methods that allow you to evaluate membership. However, in conditions where the application needs to do membership check frequently, you should opt for using sets instead of lists. Why? Because sets are hashable. The hashability requirement is enforced because, internally, Python implements sets as hash tables. One of the most significant benefits of using a hash table as the implementation mechanism is an amortized, or constant, look-up time for specific items.
2. First -In-First-Out
In some cases, we need to write codes that frequently add and remove items from the ends of the sequences. That requires items to be operated following the first-in-first-out order. Instead of using lists, that required the implementation of the pop(0) function, try to use deque.
By default, deque is designed for fast insertion and removing. To perform the FIFO operation, Python will be able to directly remove the item at the beginning of the queue without the need of shifting all the items. It means that this FIFO operation is fast.
3. Data Immutability and Hashing
Sometimes, we don’t want our data container to change, like when user enter a password or security codes. Theoretically, we could use a list to store passwords or security codes. But there are chances that the code can changed accidentally. To avoid unwanted changes, consider using tuples. In Python, tuples are immutable objects, which means their values can’t be changed after they have been created. It will return typerror if you attempt to change one of the digits. Tuples are also provide more security, a tuples object can be hashed directly in Python. As result, it will make it harder for hacker to crack the application.
From three scenarios above, we can conclude that there are container data types to suit our needs. So, we should not be restricted to only use list. Be open and always try to explore other options that provided.