Lecture Notes - Python Data Structures
Lecture Notes - Python Data Structures
Introduction:
Data structures are essential tools for organizing and manipulating data efficiently in
any programming language. In Python, there are several built-in data structures that
allow you to store, retrieve, and manipulate data in different ways. In this lecture, we will
explore some commonly used data structures in Python, including lists, tuples,
dictionaries, and sets. We will also embed code examples to demonstrate their usage
and operations.
1. Lists:
Lists are versatile data structures that can store multiple elements of different types.
They are mutable, meaning their elements can be modified. Lists are created using
square brackets ([]).
Example:
```python
# Creating a list
fruits = ['apple', 'banana', 'orange', 'mango']
# Accessing elements
print(fruits[0]) # Output: apple
# Modifying elements
fruits[1] = 'grape'
print(fruits) # Output: ['apple', 'grape', 'orange', 'mango']
# Adding elements
fruits.append('strawberry')
print(fruits) # Output: ['apple', 'grape', 'orange', 'mango', 'strawberry']
# Removing elements
fruits.remove('orange')
print(fruits) # Output: ['apple', 'grape', 'mango', 'strawberry']
```
2. Tuples:
Tuples are similar to lists but are immutable, meaning their elements cannot be
changed after creation. They are created using parentheses (()).
Example:
```python
# Creating a tuple
student = ('John', 20, 'CS')
# Accessing elements
print(student[0]) # Output: John
# Tuple unpacking
name, age, major = student
print(name, age, major) # Output: John 20 CS
```
3. Dictionaries:
Dictionaries store key-value pairs, allowing efficient lookup and retrieval of data. Keys
must be unique and immutable, while values can be of any type. Dictionaries are created
using curly braces ({}) and colons (:).
Example:
```python
# Creating a dictionary
student = {'name': 'John', 'age': 20, 'major': 'CS'}
# Accessing values
print(student['name']) # Output: John
# Modifying values
student['age'] = 21
print(student) # Output: {'name': 'John', 'age': 21, 'major': 'CS'}
4. Sets:
Sets are unordered collections of unique elements. They are useful for operations like
membership testing and eliminating duplicate values. Sets are created using curly
braces ({}) or the `set()` function.
Example:
```python
# Creating a set
fruits = {'apple', 'banana', 'orange', 'mango'}
# Adding elements
fruits.add('strawberry')
print(fruits) # Output: {'apple', 'banana', 'orange', 'mango', 'strawberry'}
# Removing elements
fruits.remove('orange')
print(fruits) # Output: {'apple', 'banana', 'mango', 'strawberry'}