Python provides several built-in data structures that are essential for writing efficient and effective programs. These data structures can be categorized into primitive (or simple) data types and non-primitive (or complex) data types. Here’s an overview of the most commonly used Python data structures:
Primitive Data Types
Integer (int)
Represents whole numbers.
Example: x = 10
Float (float)
Represents real numbers with decimal points.
Example: y = 3.14
String (str)
Represents a sequence of characters.
Example: s = “Hello, World!”
Boolean (bool)
Represents True or False values.
Example: flag = True
Non-Primitive Data Types
List
An ordered, mutable collection of items.
Allows duplicate elements.
Defined using square brackets [].
Example: lst = [1, 2, 3, “apple”, 3.14]
Tuple
An ordered, immutable collection of items.
Allows duplicate elements.
Defined using parentheses ().
Example: tpl = (1, 2, 3, “apple”, 3.14)
Set
An unordered collection of unique items.
Defined using curly braces {} or the set() function.
Example: st = {1, 2, 3, “apple”, 3.14}
Example using set(): st = set([1, 2, 3, “apple”, 3.14])
Dictionary
An unordered collection of key-value pairs.
Keys must be unique and immutable.
Defined using curly braces {} with key-value pairs separated by colons : and pairs separated by commas ,.
Example: dct = {“name”: “Alice”, “age”: 30, “city”: “New York”}
Specialized Data Structures
Deque (Double-Ended Queue)
A generalization of stacks and queues that supports adding and removing elements from either end efficiently.
Part of the collections module.
Example:
python
Copy code
from collections import deque
dq = deque([1, 2, 3])
dq.append(4)
dq.appendleft(0)
NamedTuple
A tuple subclass with named fields.
Part of the collections module.
Example:
python
Copy code
from collections import namedtuple
Point = namedtuple(‘Point’, [‘x’, ‘y’])
p = Point(1, 2)
print(p.x, p.y)
OrderedDict
A dictionary subclass that remembers the order in which keys were inserted.
Part of the collections module.
Example:
python
Copy code
from collections import OrderedDict
od = OrderedDict()
od[‘a’] = 1
od[‘b’] = 2
DefaultDict
A dictionary subclass that provides a default value for missing keys.
Part of the collections module.
Example:
python
Copy code
from collections import defaultdict
dd = defaultdict(int)
dd[‘a’] += 1
Example Usage
Here is an example demonstrating the use of these data structures in a simple program:
python
Copy code
# List
fruits = [“apple”, “banana”, “cherry”]
fruits.append(“date”)
print(fruits) # Output: [‘apple’, ‘banana’, ‘cherry’, ‘date’]
# Tuple
coordinates = (10.0, 20.0)
print(coordinates) # Output: (10.0, 20.0)
# Set
unique_numbers = {1, 2, 3, 2, 1}
unique_numbers.add(4)
print(unique_numbers) # Output: {1, 2, 3, 4}
# Dictionary
person = {“name”: “Alice”, “age”: 30}
person[“city”] = “New York”
print(person) # Output: {‘name’: ‘Alice’, ‘age’: 30, ‘city’: ‘New York’}
# Deque
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
queue.appendleft(0)
print(queue) # Output: deque([0, 1, 2, 3, 4])
# NamedTuple
from collections import namedtuple
Car = namedtuple(‘Car’, [‘make’, ‘model’, ‘year’])
my_car = Car(‘Toyota’, ‘Corolla’, 2020)
print(my_car.make) # Output: Toyota
# OrderedDict
from collections import OrderedDict
ordered_dict = OrderedDict()
ordered_dict[‘first’] = 1
ordered_dict[‘second’] = 2
print(ordered_dict) # Output: OrderedDict([(‘first’, 1), (‘second’, 2)])
# DefaultDict
from collections import defaultdict
default_dict = defaultdict(int)
default_dict[‘count’] += 1
print(default_dict) # Output: defaultdict(<class ‘int’>, {‘count’: 1})
Understanding and utilizing these data structures effectively can significantly enhance your programming capabilities in Python.