DEV Community

Venus-Kennedy
Venus-Kennedy

Posted on

One Variable, Many Values, Understanding Data Structures

Introduction

When working with Python, it is common to deal with more than one piece of information at a time. For example, a data analyst may need to store a list of customer names, transaction amounts, product categories, or examination scores. Creating a separate variable for every value would quickly become difficult to manage.

Python solves this problem through data structures.

Data structures are ways of organizing and storing multiple values so that they can be accessed, modified, and processed efficiently. Python provides several built-in data structures, including lists, tuples, sets, and dictionaries.

Understanding these structures is important because they form the foundation for working with larger datasets and data-analysis libraries such as Pandas and NumPy.

  1. Lists

A list is an ordered collection of items. Lists are created using square brackets [].

python
students = ["Alice", "Brian", "Carol", "David"]

print(students)

Output:

text
['Alice', 'Brian', 'Carol', 'David']

One of the most important characteristics of a list is that it is mutable. This means that its contents can be changed after the list has been created.

For example:

python
students[1] = "Brenda"

print(students)

Output:
text
['Alice', 'Brenda', 'Carol', 'David']

Lists can also contain different types of data:

python
student = ["Alice", 23, 85.5, True]

However, in data-processing tasks, lists are often used to store collections of related values.

** Accessing List Elements
**
Python uses indexing to access individual elements. Indexing starts at 0.

python
students = ["Alice", "Brian", "Carol", "David"]

print(students[0])
print(students[2])

Output:

text
Alice
Carol

Negative indexing can be used to access elements from the end:

python
print(students[-1])

Output:

text
David

Common List Methods

Python provides several methods for manipulating lists.

python
numbers = [10, 20, 30]

numbers.append(40)
print(numbers)

Output:

text
[10, 20, 30, 40]

append() adds an item to the end of a list. Other useful methods include insert(), remove(), and extend().

Lists are particularly useful when the order of items matters and the collection may need to change.

  1. Tuples

A tuple is another sequence data structure in Python. It is similar to a list, but tuples are immutable, meaning that their individual elements cannot be changed after the tuple is created.

Tuples are usually written using parentheses:

python
coordinates = (10, 20)

print(coordinates)

A tuple can contain different types of values:

python
student = ("Alice", 23, "Data Science")

The elements can still be accessed using indexing:

python
print(student[0])

Output:

text
Alice

However, attempting to change an element will produce an error:

python
student[0] = "Brian"

This is because tuples are immutable.

Why Use Tuples?

Tuples are useful when data should remain unchanged.

For example:

python
location = (-1.286389, 36.817223)

The coordinates can be stored as a tuple because they represent a fixed collection of related values.

Tuples can also be unpacked:

python
student = ("Alice", 23, "Data Science")

name, age, course = student

print(name)
print(age)
print(course)

This makes it convenient to work with several related values.

  1. Sets

A set is a collection of unique elements. Unlike lists and tuples, sets do not maintain elements as an indexed sequence. They are particularly useful when duplicate values need to be removed or when membership testing is important.

For example:

python
courses = {"Python", "SQL", "Python", "Statistics"}

print(courses)

The duplicate "Python" is removed.

A set can therefore be useful for identifying unique values in data.

python
cities = ["Nairobi", "Kisumu", "Nairobi", "Mombasa", "Kisumu"]

unique_cities = set(cities)

print(unique_cities)

The resulting set contains each city only once.

Sets also support operations such as union, intersection, difference, and symmetric difference.

For example:

python
python_students = {"Alice", "Brian", "Carol"}
sql_students = {"Brian", "David", "Carol"}

print(python_students & sql_students)

The & operator finds the intersection between the two sets.

The result is:

text
{'Brian', 'Carol'}

This means Brian and Carol are in both groups.

  1. Dictionaries

A dictionary stores information as key-value pairs.

For example:

python
student = {
"name": "Alice",
"age": 23,
"course": "Data Science"}

Here:

  • "name" is a key and "Alice" is its value.
  • "age" is a key and 23 is its value.
  • "course" is a key and "Data Science" is its value.

Values can be accessed using their keys:

python
print(student["name"])

Output:
text
Alice

Dictionaries are particularly useful when data has identifiable attributes.

For example, a customer record could be represented as:

python
customer = {
"customer_id": 101,
"name": "Mary",
"location": "Nairobi",
"balance": 2500}

Instead of remembering that the customer's balance is the fourth item in a list, we can simply use:

python
print(customer["balance"])

Dictionaries are mutable, so values can be added or changed:

python
customer["balance"] = 3000
customer["status"] = "Active"

Python dictionaries preserve insertion order, while their keys must be suitable hashable objects.

  1. Comparing the Main Data Structures

The four structures serve different purposes. Choosing the right structure depends on the type of information being stored and how that information will be used.

For example, if we need to store a changing collection of transaction amounts, a list would be appropriate:

python
transactions = [500, 1200, 750, 300]

If we need a fixed pair of coordinates, a tuple may be more appropriate:

python
coordinates = (-1.2864, 36.8172)

If we need to find unique transaction categories, a set would be useful:

python
categories = {"Airtime", "Withdrawal", "Airtime", "Deposit"}

If we need to represent a customer's attributes, a dictionary would be appropriate:

python
customer = {
"name": "Mary",
"age": 28,
"location": "Nairobi"}

  1. Data Structures and Data Science

Data structures are fundamental to data science because data rarely exists as a single value. Data scientists work with collections of observations, attributes, categories, and records.

For example, consider mobile money transactions:

python
transactions = [{"amount": 500, "type": "Deposit"},
{"amount": 1000, "type": "Withdrawal"},
{"amount": 750, "type": "Deposit"}]

Here, a list stores multiple transaction records, while each transaction is represented using a dictionary.

We can then use Python to process the data:

python
for transaction in transactions:
print(transaction["amount"])

Output:

text
500
1000
750

This illustrates how data structures can be combined to represent more complex datasets.

As data becomes larger and more structured, libraries such as Pandas provide specialized data structures for analysis. However, understanding Python's basic data structures makes it easier to understand how these higher-level tools work.

  1. Nested Data Structures

Python data structures can also contain other data structures.

For example:

python
students = {
"Alice": [80, 75, 90],
"Brian": [70, 85, 78],
"Carol": [92, 88, 95]}

Here, the outer structure is a dictionary, while each student's scores are stored in a list.

We can access Alice's first score using:

python
print(students["Alice"][0])

Output:

text
80

Nested structures are useful for representing hierarchical or more complex information.

  1. Why Choosing the Right Data Structure Matters

Choosing an appropriate data structure makes code easier to understand, maintain, and process.

Consider a situation where we need to determine whether a particular customer ID exists in a collection.

A set can be useful when the main requirement is membership testing:

python
customer_ids = {101, 102, 103, 104}

print(103 in customer_ids)

Output:

text
True

On the other hand, if we need to associate each customer ID with information about the customer, a dictionary would be more suitable:

python
customers = {
101: "Alice",
102: "Brian",
103: "Carol"}

print(customers[103])

Output:

text
Carol

Therefore, understanding the purpose of each structure helps a programmer choose an efficient and meaningful way to organize data.

Conclusion
**
Python's data structures provide different ways of storing and managing multiple values within a program. **Lists
are useful for ordered and changeable collections, tuples are suitable for fixed collections, sets are useful for unique values and membership operations, while dictionaries organize information using key-value pairs.

The concept behind data structures is simple: instead of creating a separate variable for every value, we can organize related information within a single structure.

For someone learning data science, this is an important foundation. Data analysis involves working with collections of observations and attributes, and understanding how Python stores and manipulates these collections makes it easier to progress toward tools such as Pandas, NumPy, and machine-learning libraries.

Ultimately, learning data structures is not just about memorizing Python syntax. It is about learning how to organize information so that it can be accessed, manipulated, and analyzed effectively.

Top comments (0)