Understanding Data Structures in Python | Python Tutorials on BeingSkilled

Data structures are essential components of programming. In Python, data structures help you store, manage, and organize data efficiently. Whether you're building a simple script or a complex application, the right data structure can make your code cleaner, faster, and more efficient.

Python comes with several built-in data structures, and in this guide, we’ll explore the most commonly used ones with practical examples. This includes lists, tuples, sets, and dictionaries.

1. Lists

A list is an ordered, mutable (changeable) collection of items. Lists are written using square brackets [].

# Example 1: Creating a list
fruits = ["apple", "banana", "cherry"]
print(fruits)
# Example 2: Modifying a list
fruits[1] = "mango"
print(fruits)
# Example 3: Looping through a list
for fruit in fruits:
    print(fruit)

2. Tuples

A tuple is similar to a list but is immutable (cannot be changed). Tuples are written using parentheses ().

# Example 4: Creating a tuple
dimensions = (1920, 1080)
print(dimensions)
# Example 5: Accessing tuple elements
print("Width:", dimensions[0])

3. Sets

A set is an unordered collection of unique elements. Sets are useful when you want to store non-duplicate values. Sets are written using curly braces {}.

# Example 6: Creating a set
colors = {"red", "green", "blue"}
print(colors)
# Example 7: Adding to a set
colors.add("yellow")
print(colors)
# Example 8: Removing duplicates using a set
nums = [1, 2, 2, 3, 4, 4]
unique_nums = set(nums)
print(unique_nums)

4. Dictionaries

A dictionary stores data in key-value pairs. It's unordered (as of Python 3.6+, it's insertion ordered), and very efficient for lookup. Dictionaries are written using curly braces {}.

# Example 9: Creating a dictionary
student = {"name": "Amit", "age": 21, "grade": "A"}
print(student)
# Example 10: Accessing values
print("Name:", student["name"])
# Example 11: Looping through a dictionary
for key, value in student.items():
    print(key, ":", value)

Why Data Structures Matter

  • Lists are great for ordered collections and quick access.
  • Tuples are ideal for fixed data that shouldn't change.
  • Sets are useful when duplicates must be avoided.
  • Dictionaries are perfect for structured data with key-value relationships.

Choosing the right data structure makes your code easier to write, read, and maintain. As you progress in Python, understanding how and when to use these structures will be a huge asset in solving real-world programming problems.