Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Data Structures in Python Part 1

The document provides an overview of various Python data structures including lists, tuples, dictionaries, sets, stacks, queues, and deques, highlighting their key characteristics and usage. It explains the properties of each structure, such as mutability, ordering, and performance, along with examples of how to create and manipulate them. Additionally, it discusses the advantages and disadvantages of stacks and queues, emphasizing their operational principles and scenarios where they are most effective.

Uploaded by

gatumudaniel18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Data Structures in Python Part 1

The document provides an overview of various Python data structures including lists, tuples, dictionaries, sets, stacks, queues, and deques, highlighting their key characteristics and usage. It explains the properties of each structure, such as mutability, ordering, and performance, along with examples of how to create and manipulate them. Additionally, it discusses the advantages and disadvantages of stacks and queues, emphasizing their operational principles and scenarios where they are most effective.

Uploaded by

gatumudaniel18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Python Data Structures

Ways to organize and store data efficiently.

Optimizes performance in algorithms.


Lists
A list in Python is an ordered, mutable collection of items. It is one of
the most commonly used data structures in Python and can store
elements of different data types, including other lists. Lists are
defined using square brackets [ ] with items separated by commas.
List Key Characteristics:
• Ordered: The order of the items is preserved. Each item has a fixed index
starting from 0.
• Mutable: We can add, remove, or modify elements after the list has been
created.
• Dynamic sizing: Lists can increase or decrease in size dynamically - no need to
declare their size ahead of time.
• Heterogeneous: Lists can contain a mix of data types (e.g., integers, strings,
other lists).
• Indexable and iterable: We can access elements using indices and loop
through them using loops like for or while.
• Supports nesting: Lists can contain other lists or even more complex
structures like dictionaries.
# Creating a list # Adding an element
numbers = [1, 2, 3, 4, 5] numbers.append(6)
print(numbers)

# Accessing an element
# Removing an element
print(numbers[0])
numbers.remove(4)
print(numbers)
# Modifying an element
numbers[2] = 10 # Iterating through the list
print(numbers[2]) for num in numbers:

print(num)
Tuples
A tuple in Python is an ordered, immutable collection of elements.
Like lists, tuples can hold a variety of data types, including other
tuples or complex objects. Tuples are defined using parentheses ( )
with elements separated by commas. While they resemble lists, the
key difference is that tuples cannot be modified after they are
created.
Tuple Key Characteristics:
• Ordered: Tuples maintain the element order, and each item can be accessed
using its index.
• Immutable: Once a tuple is created, its contents cannot be changed. This
makes tuples usable as keys in dictionaries.
• Faster than lists: Due to immutability, tuples are slightly more memory-
efficient and perform better in situations where data doesn’t need to change.
• Can contain duplicates: Tuples can hold repeated values.
• Support nesting: Tuples can contain other tuples, lists, dictionaries, etc.
• Indexable and iterable: Elements can be accessed using indexing and iterated
through with loops.
# Creating a tuple
person = ("Alice", 30, "Engineer")

# Accessing an element
print(person[0])

# Iterating through the tuple


for item in person:
print(item)
Dictionaries
A dictionary in Python is an unordered, mutable collection of key-
value pairs. Each key is unique and can be utilized to access its
associated value. Dictionaries are incredibly powerful for
representing structured data and performing fast lookups. They
are defined using curly braces { } with pairs in the format key:
value.
Dictionary Key Characteristics:
• Unordered (as of older versions): In Python versions prior to 3.7, dictionaries did not
maintain insertion order. From Python 3.7 onward, insertion order is preserved.
• Key-value mapping: Data is stored in pairs where each key maps to a specific value.
• Mutable: Values can be added, updated, or deleted after creating the dictionary.
• Keys must be unique and immutable: Common key types include strings, numbers,
and tuples. Mutable types like lists cannot be used as keys.
• Efficient lookups: Dictionary access time is nearly constant (O(1)) for most
operations, making them excellent for large datasets.
• Flexible data types: Both keys and values can be of any data type, including other
dictionaries.
# Creating a dictionary # Adding a new key-value pair
student = { "name": "John", "age": 21, student["major"] = "Computer
"grades": [88, 92, 79] } Science"
print(student)
# Accessing a value
print(student["name"]) # Removing a key-value pair
del student["grades"]
# Modifying a value print(student)
student["age"] = 22
print(student["age"]) # Iterating through the dictionary
for key, value in student.items():
print(f"{key}: {value}")
Sets
A set in Python is an unordered, mutable collection of unique
elements. Sets are useful when we want to store a group of items
without any duplicates and don’t need to maintain any specific
order. They are defined using curly braces { } or the set()
constructor, with items separated by commas.
Sets Key Characteristics:
• Unordered: The elements in a set have no defined order, and their
positions may change unpredictably.
• No duplicates: A set automatically eliminates duplicate values, making it
ideal for filtering unique items.
• Mutable: We can add or remove elements after the set is created.
• Non-indexable: Unlike lists or tuples, we cannot access set elements by
index.
• Optimized for membership tests: Checking if a value exists in a set is
very fast, typically faster than doing the same with a list.
• Supports mathematical set operations: Sets provide built-in methods
for union, intersection, difference, and symmetric difference.
# Creating a set # Membership test
fruits = {"apple", "banana", if "cherry" in fruits:
"cherry"} print("Cherry is in the
set")

# Adding an element
fruits.add("orange") # Set operations
print(fruits) set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Removing an element
fruits.remove("banana") print(set1.union(set2))
print(fruits) print(set1.intersection(set2))
print(set1.difference(set2))
Stacks
A stack is a linear data structure that operates on the Last In, First
Out (LIFO) principle. This means the last element that is added to
the stack is the first one to be removed. Stacks can be
implemented using Python lists or linked lists and are widely used
in situations where we need to keep track of operations or data in
reverse order.
Think of a stack like a stack of plates - only the topmost plate can be
removed or accessed first.
Key Characteristics:
• LIFO behavior: The last item pushed to the stack is the first one to
be popped off.
• Two primary operations:
• push: Insert an item at the top of the stack.
• pop: Discard an item from the top of the stack.
• Peek/top operation: View the item at the top without removing it.
• Multiple use cases: Used in recursion, backtracking, and parsing
algorithms.
Advantages
• Easy to implement: Stacks can be implemented easily using Python lists or
deque.
• Efficient for specific operations: Operations like undo/redo, function calls, and
backtracking are efficiently handled using stacks.
• Memory efficient: Stacks require only a small amount of additional memory
for pointer management.
• Thread-safety: Using queue.LifoQueue ensures thread-safe operations,
making it useful in concurrent applications.
• Fast performance: collections.deque offers O(1) complexity for push and pop
operations, making it an optimal choice.
• Used in algorithm implementations: Stacks are crucial in algorithms like
depth-first search (DFS) and balanced parenthesis checking.
• Supports various implementations: Python offers multiple ways to implement
stacks, catering to different performance and use-case needs.
• Better performance than lists for stacks: deque outperforms lists when used
as a stack due to optimized memory management.
Disadvantages of Stack in Python
• Limited flexibility: Since stacks operate in LIFO order, accessing elements
other than the top element is inefficient.
• Memory usage: If not managed properly, stacks can cause excessive memory
consumption, leading to stack overflow errors.
• Performance issues with lists: Lists in Python are dynamically resized, which
can cause inefficiencies in stack operations.
• Not suitable for all applications: While stacks are useful for specific scenarios,
they are not always the best choice for general data storage.
• Risk of stack overflow: If recursion depth is too high, it may lead to stack
overflow errors in recursive algorithms.
• Thread synchronization overhead: LifoQueue ensures thread safety, but this
comes at the cost of additional overhead in synchronization.
• No direct index access: Unlike lists, stacks do not allow direct access to
arbitrary elements.
Queues
A queue is a linear data structure that utilizes the First In, First Out
(FIFO) principle. In a queue, the first element that is added is the
first one to be removed - just like people waiting in line. New
elements are added at the rear (end), and elements are removed
from the front (beginning).
Queues can be implemented using lists, collections.deque, or linked
lists in Python, with deque being the most efficient and
recommended option for performance.
Adding an element to the FIFO queue is commonly referred to as an
enqueue operation, while retrieving one from it is known as a
dequeue operation.

Enqueuing and dequeuing are two independent operations that may


be taking place at different speeds. This fact makes FIFO queues the
perfect tool for buffering data in streaming scenarios and for
scheduling tasks that need to wait until some shared resource
becomes available. For example, a web server flooded with HTTP
requests might place them in a queue instead of immediately
rejecting them with an error.
Key Characteristics:
• FIFO behavior: The element inserted first is the one removed first.
• Two main operations:
• enqueue: Insert an item at the end of the queue.
• dequeue: Discard an item from the front of the queue.
• Efficient with deque: The collections.deque class offers O(1) time
complexity for append and popleft operations.
• Multiple use cases: Used in task scheduling, buffering, and
simulations.
Deque: Double-Ended Queue
A double-ended queue or deque (pronounced deck) is a more
generic data type that combines and extends the ideas behind the
stack and the queue. It allows you to enqueue or dequeue
elements from both ends in constant time at any given moment.
Therefore, a deque can work as a FIFO or a LIFO queue, as well as
anything in between and beyond.
Priority Queue: Sorted From High to Low
A priority queue is different from those you’ve seen so far because it can’t store
ordinary elements. Instead, each element must now have an associated
priority to compare against other elements. The queue will maintain a sorted
order, letting new elements join where necessary while shuffling the existing
elements around if needed. When two elements are of equal priority, they’ll
follow their insertion order.

You might also like