PYTHON COLLECTIONS
In Python, collections are containers that are used to store and organize data. Python provides several built-in collection types, each serving different purposes and offering various functionalities. Here are some of the most commonly used collection types in Python:
1. Lists (`list`):
– Lists are ordered collections of items, which can be of any data type.
– They are mutable, meaning that you can modify their elements after creation.
– Lists are defined using square brackets `[]`.
– Example: `my_list = [1, 2, 3, 4, 5]`
2. Tuples (`tuple`):
– Tuples are ordered collections similar to lists, but they are immutable, meaning that their elements cannot be changed after creation.
– Tuples are defined using parentheses `()`.
– Example: `my_tuple = (1, 2, 3, 4, 5)`
3. Sets (`set`):
– Sets are unordered collections of unique elements.
– They do not allow duplicate elements.
– Sets are defined using curly braces `{}` or the `set()` constructor.
– Example: `my_set = {1, 2, 3, 4, 5}`
4. Dictionaries (`dict`):
– Dictionaries are collections of key-value pairs.
– They are unordered and mutable.
– Keys in dictionaries must be unique and immutable (such as strings, numbers, or tuples).
– Dictionaries are defined using curly braces `{}` with key-value pairs separated by colons `:`.
– Example: `my_dict = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}`
5. Strings (`str`):
– Strings are immutable sequences of characters.
– They can be accessed similar to lists and tuples but cannot be modified in place.
– Example: `my_string = “Hello, World!”`
6. Collections Module:
– The `collections` module in Python provides additional specialized container datatypes.
– It includes named tuple, deque, Counter, OrderedDict, defaultdict, and ChainMap, among others.
– These types offer additional features and optimizations beyond the built-in collections.
These collection types offer versatile ways to organize and manipulate data in Python, catering to various requirements and scenarios encountered in programming. Each type has its own characteristics and use cases, allowing developers to choose the most suitable one based on their specific needs.