Understanding Common Pitfalls Using Lists
00:00 Time to review some of the most common errors people make when handling lists. Be careful not to mistake list aliases with list copies, to confuse shallow and deep copies, especially with nested lists.
00:13
Don’t forget that many list methods change the list in place and return None
. This is particularly important when you’re reversing or sorting lists.
00:21
And on a similar note, don’t overlook that many built-in functions return iterators, not new lists like the reversed()
or map()
functions.
00:31
Lastly, you’re not going to want to mix up append()
and extend()
. This is an easy way to introduce bugs into your code.
00:38 So what are the good use cases for lists? Well, anytime you want to keep data ordered, because in a list, the order of elements is preserved.
00:47 Storing a sequence that may grow or shrink dynamically because lists support multiple techniques for adding and removing elements.
00:54 Handling mutable data lists are a great choice if your data mutates or changes frequently. And if you need to access random values based on their indices.
01:04 Lists are designed to make looking up elements by index highly efficient.
01:10 So when is a list maybe not the best tool for the job? For storing immutable data. Instead, the Python tuple is immutable and memory efficient. For storing unique and unordered values.
01:22 If that’s what you’re looking for, consider using a set or a dict instead. Sets require elements to be unique and dictionaries don’t allow duplicate keys.
01:31
Testing for membership where item index doesn’t matter. Again, the set type is preferred because sets are optimized for membership tests using in
and not in
, or for emulating the behavior of stacks or queues.
01:46
If you’re only adding and removing items from one or both ends of a sequence, the deque
class from the collections
module is a better choice.
01:54 Alright, that’s all the advice I have to give. Meet me in the summary and we’ll wrap things up there.
Become a Member to join the conversation.