Ticker

6/recent/ticker-posts

Python Collections

Python Collections

Introduction:
Python provides several built-in collections that allow you to efficiently manage and store multiple elements in a single container. These collections offer various data structures with different functionalities to suit different use cases.

1. Lists:
Lists are ordered collections that can hold heterogeneous data types. They allow indexing, slicing, and offer various methods for manipulation. Below is an example of a Python list:

python
fruits = ["apple", "banana", "orange"]

2. Tuples:
Tuples are similar to lists but are immutable, meaning their elements cannot be modified after creation. They are usually used when data should not be changed. Here's a tuple example:

python
coordinates = (10, 20)

3. Sets:
Sets are unordered collections of unique elements. They do not allow duplicate values and are useful for eliminating duplicates from other collections. Example:

python
unique_numbers = {1, 2, 3, 4}

4. Dictionaries:
Dictionaries are key-value pairs where each key is associated with a value. They are used to store data in the form of key-value mappings. Example:

python
student_info = {"name": "Alice", "age": 25, "major": "Computer Science"}

5. Deque:
A deque (double-ended queue) is a data structure that allows fast append and pop operations from both ends. It is useful for implementing queues and stacks efficiently. Import deque from collections module:

python
from collections import deque

my_queue = deque()
my_queue.append(1) # enqueue operation
my_queue.append(2)
my_queue.popleft() # dequeue operation

6. NamedTuple:
NamedTuple is a subclass of tuples that allows accessing elements by name, making code more readable and self-documenting. Define a NamedTuple using the namedtuple function from the collections module:

python
from collections import namedtuple

Person = namedtuple("Person", ["name", "age", "gender"])
alice = Person(name="Alice", age=30, gender="Female")

These Python collections offer powerful tools for handling various data structures and are essential for any Python programmer. Always choose the collection that best suits your specific use case.

Post a Comment

0 Comments