- Aliases
- and operator
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Floats
- For loops
- Formatted strings
- Functions
- Generator
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- OOP
- or operator
- Parameters
- print() function
- Random module
- range() function
- Recursion
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String join() method
- String replace() method
- String split() method
- Strings
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
- Zip function
PYTHON
Python Data Structures: Syntax, Usage, and Examples
Python data structures are essential for organizing, storing, and manipulating data efficiently. They help programmers manage collections of data and perform operations such as searching, sorting, and modifying data. Python provides built-in data structures like lists, tuples, sets, and dictionaries, as well as more advanced structures like trees, graphs, queues, linked lists, and hash tables. Understanding these structures and when to use them is crucial for writing efficient and readable code.
How to Use Data Structures in Python
Python has several built-in data structures, each optimized for different use cases. The four most commonly used ones are:
- Lists: Ordered, mutable collections that allow duplicates
- Tuples: Ordered, immutable collections
- Sets: Unordered collections with unique elements
- Dictionaries: Key-value pairs for fast lookups
They can store integers, strings, booleans, and other data types. Developers often leverage them in Python programming for projects spanning data analysis, machine learning, and general dsa (data structures and algorithms) tasks.
Lists in Python
A Python list is an ordered collection defined with square brackets and commas that allows adding, removing, and modifying elements. Lists support indexing and slicing, making them easy to manipulate.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
# Modifying a list
fruits.append("orange") # Adds an item
fruits.remove("banana") # Removes an item
print(fruits) # Output: ['apple', 'cherry', 'orange']
Tuples in Python
Tuples look like lists but use parentheses instead of square brackets, and they’re immutable, meaning their values cannot be changed after creation.
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
Sets in Python
A set is an unordered collection of unique elements. It is useful for removing duplicates and performing mathematical set operations. They ignore repeated items and are handy when working with iterable data
numbers = {1, 2, 3, 3, 4}
print(numbers) # Output: {1, 2, 3, 4}
# Adding elements to a set
numbers.add(5)
print(numbers) # Output: {1, 2, 3, 4, 5}
Dictionaries in Python
Often referred to as a Python dictionary or dict, dictionaries store key-value pairs and allow for quick lookups and modifications.
person = {"name": "Alice", "age": 30}
print(person["name"]) # Output: Alice
# Adding a new key-value pair
person["city"] = "New York"
print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
When to Use Data Structures in Python
Selecting the right data structure depends on how your data will be accessed and modified. This is a core topic in computer science and data science, where the choice can affect performance in areas like data analysis, machine learning, and other complex applications.
Lists
Use lists when you need:
- Ordered data storage
- Quick addition of items at the end of the list
- Support for duplicate values
Example: Storing a list of tasks in a to-do application.
tasks = ["Buy groceries", "Finish project", "Call mom"]
Tuples
Use tuples when:
- Data should remain unchanged (e.g., coordinates, days of the week)
- Memory efficiency is important
Example: Storing constant data like RGB color values.
color = (255, 0, 0) # Red color in RGB format
Sets
Use sets when:
- You need unique elements (e.g., filtering duplicate email addresses)
- Mathematical set operations like unions and intersections are required
Example: Finding common friends between two social media users.
friends_a = {"Alice", "Bob", "Charlie"}
friends_b = {"Charlie", "David", "Eve"}
common_friends = friends_a & friends_b # Output: {'Charlie'}
Dictionaries
Use dictionaries when:
- You need to store key-value pairs for fast lookups
- You require fast updates and retrievals
Example: Storing product details in an e-commerce application.
product = {"name": "Laptop", "price": 999, "stock": 5}
print(product["price"]) # Output: 999
Examples of Data Structures in Python
Using a Dictionary for Fast Lookups
Dictionaries are optimized for key-based searches, making them ideal for scenarios where data retrieval needs to be fast.
employee_salaries = {"Alice": 50000, "Bob": 60000, "Charlie": 70000}
print(employee_salaries.get("Bob")) # Output: 60000
Set Operations
Sets are useful for handling unique elements and performing operations like unions and intersections. They’re especially popular in data analysis and JavaScript or Java conversions when working with distinct elements.
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union_set = set1 | set2 # {1, 2, 3, 4, 5, 6}
intersection_set = set1 & set2 # {3, 4}
Queue and Stack Behavior
Data structures like queues (using first-in-first-out or FIFO order) and stacks (using lifo, last-in-first-out) can be simulated with lists or specialized classes in Python. Collections like deque offer efficient appends and pops from both ends.
from collections import deque
# Creating a queue
line = deque(["Alice", "Bob", "Charlie"])
line.append("David") # Enqueue at the back
served = line.popleft() # Dequeue from the front
Implementing a Tree Data Structure
Trees store data hierarchically and are commonly used in searching and sorting. A binary search tree (BST) is a simple example.
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, value):
if root is None:
return Node(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
root = insert(None, 10)
insert(root, 5)
insert(root, 15)
Arrays in Python
Though Python doesn’t have a distinct built-in arrays type like C or Java, we often use lists or Numpy arrays for numeric data. Numpy arrays are popular in data science and machine learning due to their efficiency.
import numpy as np
arr = np.array([1, 2, 3])
print(arr) # [1 2 3]
Learn More About Data Structures in Python
Python Data Structures and Algorithms
Understanding data structures is crucial for writing optimized code. Many algorithms, such as sorting and searching, rely on efficient data storage and retrieval.
What Are Data Structures in Python?
Data structures define how data is organized and accessed. Python provides built-in structures like lists and dictionaries, while custom structures like trees and graphs allow for more specialized use cases.
Trees in Data Structures
Trees are hierarchical structures used in databases, file systems, and search algorithms. Binary trees, heaps, and B-trees are some common tree structures.
Python data structures provide powerful tools for managing data efficiently. Choosing the right one ensures optimal performance and scalability in your programs.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.