Data Structures in Python

Data Structures in Python

Lists, Tuples, Sets, and Dictionaries

Data structures are the backbone of efficient programming. In Python, the built-in data structures—**lists, tuples, sets, and dictionaries**—offer flexibility and power. This article explores their features, real-world use cases, and Pythonic techniques to manipulate them effectively.


1. Lists: The Go-To for Ordered Collections

Lists are mutable, ordered collections that can hold heterogeneous data types.

Syntax: my_list = [1, 2, 3, "Python"]

Key Features:

  • Dynamic sizing.
  • Supports indexing and slicing.
  • Wide range of built-in methods (`append()`, pop(), sort(), etc.).

Real-World Scenario:

  • Use lists to store sequential data, like a to-do list in a task management app.

  Example:   
  tasks = ["Email client", "Submit report", "Team meeting"]
  tasks.append("Review code")
  print(tasks)  # ['Email client', 'Submit report', 'Team meeting', 'Review code']        

Pythonic Techniques:

List comprehensions for concise operations:

squares = [x**2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]        

2. Tuples: Immutable and Lightweight

Tuples are immutable, ordered collections, often used for fixed sets of data.

Syntax: my_tuple = (1, "Python", 3.14)

Key Features:

  • Faster than lists due to immutability.
  • Can be used as dictionary keys.
  • Support unpacking.

Real-World Scenario:

Use tuples to represent fixed pairs, like latitude and longitude in a GPS app.

Example:  
location = (37.7749, -122.4194)  # San Francisco coordinates        

Pythonic Techniques:

Unpacking tuples:

x, y = location
print(f"x: {x}, y: {y}")  # x: 37.7749, y: -122.4194        

3. Sets: Unordered Collections of Unique Items

Sets store unique, unordered items and are mutable.

Syntax: my_set = {1, 2, 3}

Key Features:

  • Fast membership testing.
  • Support for mathematical operations like union and intersection.

Real-World Scenario:

Use sets to remove duplicates from a list of user inputs.

users = ["Alice", "Bob", "Alice", "Charlie"]
unique_users = set(users)
print(unique_users)  # {'Alice', 'Charlie', 'Bob'}        

Pythonic Techniques:

Set operations:

set_a = {1, 2, 3}
set_b = {3, 4, 5}
print(set_a & set_b)  # Intersection: {3}
print(set_a | set_b)  # Union: {1, 2, 3, 4, 5}        

4. Dictionaries: Key-Value Pairs

Dictionaries are mutable collections of key-value pairs, offering O(1) lookups.

Syntax: my_dict = {"name": "Alice", "age": 30}

Key Features:

  • Keys must be immutable.
  • Supports nested dictionaries.

Real-World Scenario:

Use dictionaries for storing user profiles in an app.

user_profile = {
"username": "alice123",
"email": "alice@example.com",
"age": 30
 }
print(user_profile["email"])  # alice@example.com        

Pythonic Techniques:

Dictionary comprehensions:

squares = {x: x**2 for x in range(5)}
print(squares)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}        

Article content

Conclusion

Choosing the right data structure is essential for writing clean, efficient Python code. Whether you’re iterating over a list, unpacking a tuple, removing duplicates with a set, or storing key-value pairs in a dictionary, Python’s flexibility lets you work smarter. What’s your go-to data structure in Python?


To view or add a comment, sign in

More articles by Suganya G

  • Understanding Self-Attention in Transformer Architecture

    Self-attention is a crucial mechanism in transformers; it enables them to focus on specific parts of the input sequence…

  • Transformers: The architecture that redefined AI

    Introduction Deep learning has seen multiple breakthroughs, but few have had the transformative impact of the…

  • The Art and Science of Prompt Engineering

    In the evolving landscape of artificial intelligence, prompt engineering plays a crucial role in optimizing the…

  • Multiprocessing in Python

    The multiprocessing module in Python allows the creation of multiple processes, enabling parallel execution of tasks…

  • Unlocking the Power of Machine Learning Algorithms in Data Analysis

    Introduction to Data Analysis Data analysis is the process of examining, organizing, and interpreting raw data to…

    2 Comments
  • Python Libraries and Modules for Data Science and APIs

    Python's standard library is packed with modules that simplify development by providing powerful built-in…

  • Decoding AI: A Dive into LLMs and Their Impact on the Future

    In recent years, generative artificial intelligence (AI) has emerged as a transformative force across industries…

    3 Comments
  • Python OOP Essentials

    Object-Oriented Programming (OOP) is a paradigm that models data as objects and organizes code using principles like…

    3 Comments
  • Data Structures in Python

    Lists, Tuples, Sets, and Dictionaries Data structures are the backbone of efficient programming. In Python, the…

    2 Comments
  • Python - Lists vs Dictionaries

    Here’s an example using lists and dictionaries separately for the same task—aggregating sales data—and a comparison of…

    2 Comments

Explore content categories