PYTHON Tutorial

Basic Data Structures

Introduction

Data structures are fundamental building blocks for organizing and storing data in a computer program. Python offers a versatile range of data structures, each tailored for specific applications.

Key Concepts

  • Lists: Ordered collections of items that can be accessed by index.
  • Dictionaries: Key-value pairs where keys are unique and values can be any data type.
  • Tuples: Ordered sequences of immutable (unchangeable) items.
  • Sets: Unordered collections of unique items that do not allow duplicates.

Python Example

# Lists
my_list = [1, 2, 3, 4, 5]  # Declare a list
my_list.append(6)  # Add an element to the end
my_list.remove(2)  # Remove an element

# Dictionaries
my_dict = {"name": "John", "age": 30}  # Declare a dictionary
my_dict["job"] = "Software Engineer"  # Add a key-value pair
del my_dict["age"]  # Delete a key-value pair

# Tuples
my_tuple = (1, 2, 3)  # Declare a tuple
# Tuples are immutable, so we cannot modify them

# Sets
my_set = {1, 2, 3, 4}  # Declare a set
my_set.add(5)  # Add an element
my_set.remove(2)  # Remove an element

Practical Steps

  • Choose the appropriate data structure: Consider the specific needs of your application, such as whether you need ordered or unordered data or if you need to allow duplicates.
  • Initialize the data structure: Use the syntax provided above to declare a new data structure.
  • Manipulate the data structure: Use methods such as append, remove, add, and delete to modify the data structure as needed.
  • Access data: Use indexing or key access to retrieve specific elements from the data structure.