Python Data Structures and File Operations Tutorial
This tutorial introduces Python's core data structures—lists, dictionaries, sets, and tuples—and demonstrates essential file operations for text, CSV, and JSON formats, providing practical code examples for each concept and explains their characteristics, common operations, and best practices for efficient programming.
Python provides several built-in data structures, each with specific uses and characteristics.
1. List (List)
Characteristics: ordered, mutable, allows duplicate elements.
Operations:
Creating a list:
fruits = ["apple", "banana", "cherry"]Accessing elements:
print(fruits[0]) # Output: appleAdding elements:
fruits.append("orange") # Add to end
fruits.insert(1, "grape") # Insert at positionRemoving elements:
fruits.remove("banana") # Remove first match
del fruits[0] # Delete by indexIterating:
for fruit in fruits:
print(fruit)2. Dictionary (Dictionary)
Characteristics: unordered (insertion order preserved in Python 3.7+), stores key‑value pairs.
Operations:
Creating a dictionary:
person = {"name": "Alice", "age": 30, "city": "New York"}Accessing values:
print(person["name"]) # Output: Alice
print(person.get("age")) # Output: 30Updating or adding:
person["age"] = 31 # Update existing key
person["job"] = "Engineer" # Add new key‑valueDeleting:
del person["city"] # Remove key 'city'Iterating:
for key, value in person.items():
print(f"{key}: {value}")3. Set (Set)
Characteristics: unordered, no duplicate elements.
Operations:
Creating a set:
colors = {"red", "green", "blue"}Adding elements:
colors.add("yellow")Removing elements:
colors.remove("red") # Raises KeyError if missing
colors.discard("purple") # No error if missingSet operations:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
union_set = set1.union(set2) # Union
intersection_set = set1.intersection(set2) # Intersection
difference_set = set1.difference(set2) # Difference4. Tuple (Tuple)
Characteristics: ordered, immutable.
Operations:
Creating a tuple:
coordinates = (10.0, 20.0)Accessing elements:
print(coordinates[0]) # Output: 10.0Iterating:
for coord in coordinates:
print(coord)Note: Tuples are immutable; to change, reassign the whole tuple.
File Operations
Python provides simple tools for reading, writing, and managing files.
1. Text Files
Reading:
with open('example.txt', 'r') as file:
content = file.read()
print(content)Writing:
with open('output.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a new line.")Appending:
with open('output.txt', 'a') as file:
file.write("\nAdding more text.")2. CSV Files
Using the csv module.
Reading:
import csv
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(', '.join(row))Writing:
import csv
data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles']
]
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)3. JSON Files
Using the json module.
Reading:
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)Writing:
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
with open('output.json', 'w') as file:
json.dump(data, file, indent=4) # Indented for readabilitySummary
Through the above content, you can see that Python provides rich and easy‑to‑use data structures and file‑operation methods. Mastering these basics helps you write code more efficiently and handle various data and file types with ease. If you have further questions or need additional help, feel free to ask!
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.