List, Tuples and Dict
List are the ordered collection of items. It can store elements of different types and is mutable, meaning it's content can be changed after creation.
Some of the methods are: append(), extend(), insert(), remove(), pop(), sort(), reverse(), len()
A tuple is also an ordered collection of items that can hold different data types. Unlike lists, tuples are immutable, meaning they cannot be modified after creation. Frequently used methods: count(), index(), len()
A dictionary stores data as key-value pairs. They are mutable. The key must be immutable and unique. So valid keys are - string, integer, tuple. Methods: keys(), values(), items(), update(), pop(), clear()
List vs Tuples
- The key difference between a List and a Tuple is that Lists are mutable whereas Tuples are immutable.
- Tuples generally use less memory and can be slightly faster for read-only operations, because they are immutable and have a more compact internal implementation compared to lists
- Tuples can be used as dictionary keys because they are hashable (if all elements inside are immutable).
- Lists cannot be used as dictionary keys because they are mutable and therefore not hashable.
Set vs Dict
- Set are the unordered collection of unique elements. Set are mutable but elements must be hashable (immutable)
- Membership lookup (
inoperator) in a set is O(1) on average because sets are implemented using a hash table. - A Dictionary stores data as key-value pairs. Keys must be unique and immutable. Values can be any datatype.
"A Set is used when we need uniqueness and fast membership checks, while a Dictionary is used when we need key-value mappings with fast lookups"