
Data Structures in Python
Python
Thu Nov 23 2023
I have been working with python lately and felt like covering some basics. To begin, i want to go over the basic data structures and what they look like in python.
1. List
- Description: An ordered, mutable collection of items.
- Example:
# Creating a list
fruits = ["apple", "banana", "cherry"]
# Adding an item
fruits.append("orange")python
2. Tuple
- Description: An ordered, immutable collection of items.
- Example:
# Creating a tuple
coordinates = (10.0, 20.0)python
3. Set
- Description: An unordered collection of unique items.
- Example:
# Creating a set
unique_numbers = {1, 2, 3, 4, 4, 5}
# Duplicates are removedpython
4. Dictionary
- Description: An unordered collection of key-value pairs.
- Example:
# Creating a dictionary
person = {"name": "Evan", "age": 33}
# Accessing items
name = person["name"]python
5. String
- Description: An immutable sequence of characters.
- Example:
greeting = "Hello, Internet!"python
6. Byte Array
- Description: A mutable sequence of bytes.
- Example:
bytes_arr = bytearray([50, 100, 76, 72])python
7. Bytes
- Description: An immutable sequence of bytes.
- Example:
immutable_bytes = b'Hello'python
8. Deque (from collections)
- Description: A double-ended queue allowing append and pop operations from both ends.
- Example:
from collections import deque
dq = deque([1, 2, 3])
dq.appendleft(0) # deque is now [0, 1, 2, 3]
python
9. Counter (from collections)
- Description: A dictionary subclass for counting hashable items.
- Example:
from collections import Counter
word_counts = Counter("banana")python
10. OrderedDict (from collections)
- Description: A dictionary subclass that remembers the order entries were added.
- Example:
from collections import OrderedDict
ordered_dict = OrderedDict(one=1, two=2)python
11. defaultdict (from collections)
- Description: A dictionary subclass that calls a factory function to supply missing values.
- Example:
from collections import defaultdict
dd = defaultdict(int)
dd['key'] += 1 # No KeyError for missing 'key'python
12. namedtuple (from collections)
- Description: A factory function for creating tuple subclasses with named fields.
- Example:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, y=20)python
Each of these have their specific, unique usecases and some are more simplistic than others (strings, for example). I will go into more depth with some of these in subsequent blog posts. Happy Coding!

