Contents
Roadmap info from roadmap website
Lists, Tuples, Sets, and Dictionaries
Lists: are just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python.
Tuple: A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists that are mutable.
Set: A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Pythonβs set class represents the mathematical notion of a set. s Dictionary: In python, Dictionary is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
Visit the following resources to learn more:
- @video@Difference Between List, Tuple, Set and Dictionary in Python
- @article@Tuples vs. Lists vs. Sets in Python
- @article@Python for Beginners: Lists
- @article@Python for Beginners: When and How to Use Tuples
Feature | Lists | Tuples | Sets | Dictionaries |
---|---|---|---|---|
Syntax | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} | {'key1': 'value1', 'key2': 'value2'} |
Ordered | Yes | Yes | No | Yes (insertion order since Python 3.7) |
Mutable | Yes | No | Yes | Yes |
Allows Duplicates | Yes | Yes | No | Keys: No, Values: Yes |
Indexing | Yes | Yes | No | Keys used for accessing values |
Heterogeneous | Yes | Yes | Yes | Yes |
Use Case | Ordered collection of items | Immutable ordered collection | Unordered collection of unique items | Collection of key-value pairs |
Methods Available | Many (e.g., append, pop, sort) | Few (e.g., count, index) | Few (e.g., add, remove, union) | Many (e.g., keys, values, items, get) |
Memory Efficiency | Less efficient than tuples | More efficient than lists | Varies (no duplicates, so potentially more efficient for unique items) | Depends on the size and hash function of keys |
Iteration | Yes | Yes | Yes | Yes |
Creation | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} | {'key': 'value'} |
Comprehensions | List comprehensions ([x for x in iterable] ) | Not directly, but can cast to list comprehension | Set comprehensions ({x for x in iterable} ) | Dictionary comprehensions ({k: v for k, v in iterable} ) |
Key Characteristics | Flexible, mutable, and allows duplicates | Immutable, can be used as keys in dictionaries | Unordered, no duplicates allowed | Maps unique keys to values |