Data Structures in Python
Tags: python, webdev, beginners, tutorial
Published: 2024-01-19 14:43:42

## Data Structure

A data structure is a fundamental concept in computer science, providing an organized and efficient way to store and manipulate data. It encompasses the relationship between data, the associated operations, and the [algorithms](https://en.wikipedia.org/wiki/Algorithm) governing those operations. The choice of a data structure is crucial, and dependent on the problem at hand and the recurring operations.


### List

A list is like an array, declared in other languages. It's a mutable data structure that allows you to organize and store a collection of elements. Lists are defined by enclosing the elements in brackets `[]` and separating them with commas.

The list maintains the order of elements as they are inserted. Each element has an index, starting from zero.


![A list diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgbxryg3t0fpvc6ipffu.png)


The list can be modified after creation. You can add, remove, or modify elements in a list.


```
# Creating a list
fruits = ['apple', 'orange', 'banana']

# Accessing elements
print(fruits[0])  # Output: apple

# Modifying elements
fruits[1] = 'grape'
print(fruits)  # Output: ['apple', 'grape', 'banana']

# Adding elements
fruits.append('kiwi')
print(fruits)  # Output: ['apple', 'grape', 'banana', 'kiwi']

# Removing elements
fruits.remove('apple')
print(fruits)  # Output: ['grape', 'banana', 'kiwi']
```

Also, a list can contain elements of different data types, including numbers, strings, other lists, or even custom objects.

```
Example of a list containing both numbers and letter
`my_list = [1, 2, 3, 'a', 'b', 'c']`
```
**_Lists accommodate diverse data types, making them widely used for scenarios requiring an ordered, mutable collection._**

### Tuple:Immutable Data Collections

Tuples, similar to lists, store ordered elements but differ in immutability. Once created, tuples cannot be modified, making them suitable for situations requiring data integrity:

```
# Creating a tuple
coordinates = (3, 4)

# Unpacking a tuple
x, y = coordinates
print(f"x: {x}, y: {y}")  # Output: x: 3, y: 4

# Tuples as keys in dictionaries
location_info = {(1, 2): 'Point A', (3, 4): 'Point B'}
print(location_info[(1, 2)])  # Output: Point A
```
**_Tuples are favored when constant data is needed throughout program execution or when used as keys in dictionaries._**

### Sets: Unordered Unique Elements

Sets in Python are unordered collections of unique elements, defined by curly braces `{}` or the `set()` constructor. Sets efficiently handle tasks like union, intersection, and difference:

_Creating a Set_

```
fruits = {'apple', 'orange', 'banana'}

```
_Adding Elements_

```
fruits.add('kiwi')

```
_Removing Elements_

```
fruits.remove('orange')

```
_Using discard() method to remove an element if it exists, or do nothing if it doesn't._

```
fruits.discard('grape')

```
_Set Operations:_
_Union: Combining two sets._

```
more_fruits = {'kiwi', 'grape', 'apple'}
all_fruits = fruits.union(more_fruits)
```

_Intersection: Finding common elements between two sets._

```
common_fruits = fruits.intersection(more_fruits)
```

_Difference: Finding elements in one set but not in the other._

```
unique_fruits = fruits.difference(more_fruits)

```
**_Sets are valuable for managing collections with unique elements, such as eliminating duplicates or checking for specific elements._**

### Dictionaries: Key-Value Data Storage

In Python, a dictionary is an unordered collection of data values used to store and retrieve data in key-value pairs. Dictionaries are defined using curly braces {} and consist of key-value pairs separated by commas.

Unlike lists and tuples, Dictionary does not maintain any order among the elements. Dictionary-like lists are mutable, you can add, remove, or modify key-value pairs after the dictionary is created.

```
# Creating a dictionary
student_info = {'name': 'John', 'age': 20, 'grade': 'A'}

# Accessing values
print(student_info['name'])  # Output: John

# Modifying values
student_info['age'] = 21
print(student_info)  # Output: {'name': 'John', 'age': 21, 'grade': 'A'}

# Dictionary comprehension
squared_numbers = {x: x**2 for x in range(5)}
print(squared_numbers)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
```
**_Dictionaries excel in tasks involving key-based data access, making them optimal for mapping keys to values and organizing data efficiently._**

### Strings and Their Manipulation

String manipulation is a crucial aspect of programming, allowing efficient processing and modification of textual data. Techniques include:

- _Concatenation and String formatting:_

Combining two or more strings and Creating formatted strings using various methods

```
greeting = 'Hello'
name = 'John'
message = f"{greeting}, {name}!"
print(message)  # Output: Hello, John!
```

- _Indexing and Slicing:_
Accessing individual characters or extracting substrings.

```
first_char = message[0]
last_name = name[1:]

```
_Regular Expressions:_

Advanced string manipulation using patterns.

```
import re
pattern = re.compile(r'\b\w{5}\b')
matches = pattern.findall(sentence)

```

**_Mastering string manipulation is essential for various applications, from simple concatenation to complex operations like pattern matching._**


### Exercise-Project: Building a To-Do List Application

Implementing a to-do list application using lists and dictionaries provides hands-on experience in applying these data structures in practical scenarios.
Refer to [this example](https://github.com/kihuni/Explore-Backend/blob/main/Intro-to-Python-article/Python_Web_Development/Data_structure/to-do-list.py)

### Conclusion


Understanding data structures and their optimal use cases enhances your ability to write efficient and scalable Python code. This proficiency equips you to tackle a broad spectrum of programming challenges with confidence.