Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHDERUPTENFRES

Elysia Tools

Navigation

Programming Languages

Python examples: output, collections and file handling

Choose Python snippets for output, list operations and file I/O.

Samples

Entries inside this sample collection

CodepythonSimple

Python Hello World

Basic Python Hello World program and fundamental syntax examples

Difficulty

2/10

Estimated time

10 min

Tags

python, programming, beginner

Prerequisites

Basic programming concepts

python
# Python Hello World Examples

# 1. Basic Hello World
print("Hello, World!")

# 2. Hello World with variable
message = "Hello, World!"
print(message)

# 3. Hello World with function
def say_hello():
    return "Hello, World!"

print(say_hello())

# 4. Hello World with function parameters
def greet(name):
    return f"Hello, {name}!"

print(greet("World"))
print(greet("Python"))

# 5. Hello World with class
class Greeter:
    def __init__(self, message="Hello, World!"):
        self.message = message
    
    def greet(self):
        return self.message

greeter = Greeter()
print(greeter.greet())

# 6. Hello World with user input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# 7. Hello World multiple times
for i in range(5):
    print(f"Hello, World! {i + 1}")

# 8. Hello World with list
hellos = ["Hello", "Bonjour", "Hola", "Ciao", "こんにちは"]
for greeting in hellos:
    print(f"{greeting}, World!")

# 9. Hello World with dictionary
greetings = {
    "en": "Hello",
    "es": "Hola", 
    "fr": "Bonjour",
    "de": "Hallo",
    "ja": "こんにちは"
}

for lang, greeting in greetings.items():
    print(f"{greeting}, World! ({lang})")

# 10. Hello World with file I/O
with open("hello.txt", "w") as f:
    f.write("Hello, World!")

with open("hello.txt", "r") as f:
    content = f.read()
    print(f"From file: {content}")

# Basic data types examples
integer = 42
float_num = 3.14
string = "Python"
is_boolean = True
list_data = [1, 2, 3, 4, 5]
tuple_data = (1, 2, 3)
dictionary = {"name": "Python", "version": 3.9}

print(f"Integer: {integer}, Type: {type(integer)}")
print(f"Float: {float_num}, Type: {type(float_num)}")
print(f"String: {string}, Type: {type(string)}")
print(f"Boolean: {is_boolean}, Type: {type(is_boolean)}")
print(f"List: {list_data}, Type: {type(list_data)}")
print(f"Tuple: {tuple_data}, Type: {type(tuple_data)}")
print(f"Dictionary: {dictionary}, Type: {type(dictionary)}")

# Control flow examples
age = 18
if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

# Loop examples
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# While loop example
count = 0
while count < 3:
    print(f"Count: {count}")
    count += 1

# List comprehensions
squares = [x**2 for x in range(10)]
print(f"Squares: {squares}")

# Exception handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("This always runs")
CodepythonIntermediate

Python Data Structures

Comprehensive examples of Python data structures and their operations

Difficulty

5/10

Estimated time

20 min

Tags

python, data structures, programming

Prerequisites

Basic Python syntax

python
# Python Data Structures Examples

# 1. Lists (Mutable sequences)
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = list(range(1, 6))  # [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# List operations
fruits.append("orange")           # Add to end
fruits.insert(1, "grape")        # Insert at index
fruits.remove("banana")          # Remove first occurrence
popped = fruits.pop()            # Remove and return last item
fruits[0] = "kiwi"               # Update item

# List slicing
print(fruits[1:3])      # Items from index 1 to 2
print(fruits[:2])       # Items from start to index 1
print(fruits[2:])       # Items from index 2 to end

# List comprehensions
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

# 2. Tuples (Immutable sequences)
# Creating tuples
coordinates = (10, 20)
single_item = (42,)      # Note the comma
empty_tuple = ()

# Tuple operations
x, y = coordinates      # Unpacking
print(f"X: {x}, Y: {y}")

# Named tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(10, 20)
print(f"Point: ({p1.x}, {p1.y})")

# 3. Dictionaries (Key-value pairs)
# Creating dictionaries
student = {
    "name": "Alice",
    "age": 20,
    "grades": [85, 90, 78]
}

# Dictionary operations
student["major"] = "Computer Science"    # Add key-value pair
age = student.get("age", 0)              # Get with default
del student["grades"]                    # Delete key-value pair

# Dictionary methods
keys = student.keys()
values = student.values()
items = student.items()

# Dictionary comprehensions
squares_dict = {x: x**2 for x in range(6)}
print(f"Squares dictionary: {squares_dict}")

# 4. Sets (Unique elements)
# Creating sets
unique_numbers = {1, 2, 3, 2, 1}  # {1, 2, 3}
from_set = set([1, 2, 3, 2, 1])

# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

print(f"Union: {set_a | set_b}")           # {1, 2, 3, 4, 5, 6}
print(f"Intersection: {set_a & set_b}")    # {3, 4}
print(f"Difference: {set_a - set_b}")      # {1, 2}
print(f"Symmetric difference: {set_a ^ set_b}")  # {1, 2, 5, 6}

# 5. Strings (Immutable sequences)
text = "Hello, Python!"
print(f"Length: {len(text)}")
print(f"Upper: {text.upper()}")
print(f"Lower: {text.lower()}")
print(f"Replace: {text.replace('Python', 'World')}")

# String methods
words = text.split(", ")
print(f"Words: {words}")
joined = "-".join(words)
print(f"Joined: {joined}")

# 6. Stack and Queue using lists
# Stack (LIFO)
stack = []
stack.append(1)    # push
stack.append(2)
stack.append(3)
top_item = stack.pop()  # pop

# Queue (FIFO) - using collections.deque
from collections import deque
queue = deque()
queue.append(1)    # enqueue
queue.append(2)
queue.append(3)
front_item = queue.popleft()  # dequeue

# 7. Nested data structures
# List of dictionaries
students = [
    {"name": "Alice", "age": 20, "grades": [85, 90, 78]},
    {"name": "Bob", "age": 22, "grades": [92, 88, 95]},
    {"name": "Charlie", "age": 21, "grades": [78, 85, 82]}
]

# Accessing nested data
for student in students:
    avg_grade = sum(student["grades"]) / len(student["grades"])
    print(f"{student['name']}: Average grade = {avg_grade:.1f}")

# 8. Advanced list operations
# Sorting
numbers = [64, 34, 25, 12, 22, 11, 90]
numbers.sort()                    # In-place sort
sorted_numbers = sorted(numbers, reverse=True)  # New sorted list

# Sorting with custom key
students.sort(key=lambda x: x["age"])

# 9. Dictionary with complex keys
complex_dict = {
    (1, 2): "Point at (1,2)",
    "nested": {"inner": "value"},
    frozenset([1, 2, 3]): "Immutable set as key"
}

# 10. Performance comparison
import time

# List vs Set for membership testing
large_list = list(range(100000))
large_set = set(large_list)

# Test list membership
start = time.time()
result = 99999 in large_list
list_time = time.time() - start

# Test set membership
start = time.time()
result = 99999 in large_set
set_time = time.time() - start

print(f"List membership time: {list_time:.6f}s")
print(f"Set membership time: {set_time:.6f}s")
CodepythonIntermediate

Python File Handling

File I/O operations and file system manipulation in Python

Difficulty

6/10

Estimated time

25 min

Tags

python, file operations, i/o

Prerequisites

Basic Python syntax

python
# Python File Handling Examples

import os
import json
import csv
from pathlib import Path

# 1. Basic file operations
# Write to file
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a file handling example.\n")
    file.write("Python makes file operations easy.\n")

# Read from file
with open("example.txt", "r") as file:
    content = file.read()
    print("File content:")
    print(content)

# Read line by line
with open("example.txt", "r") as file:
    print("\nReading line by line:")
    for line_num, line in enumerate(file, 1):
        print(f"Line {line_num}: {line.strip()}")

# 2. Different file modes
# Append mode
with open("example.txt", "a") as file:
    file.write("\nAppended text at the end.")

# Read and write mode (r+)
with open("example.txt", "r+") as file:
    content = file.read()
    file.seek(0)  # Go to beginning
    file.write("MODIFIED: " + content)

# 3. Working with binary files
# Write binary data
data = bytes(range(256))  # 0-255 bytes
with open("binary.bin", "wb") as file:
    file.write(data)

# Read binary data
with open("binary.bin", "rb") as file:
    binary_data = file.read()
    print(f"\nBinary data length: {len(binary_data)} bytes")

# 4. JSON file operations
data_to_save = {
    "name": "John Doe",
    "age": 30,
    "skills": ["Python", "JavaScript", "SQL"],
    "address": {
        "street": "123 Main St",
        "city": "New York"
    }
}

# Write JSON to file
with open("data.json", "w") as file:
    json.dump(data_to_save, file, indent=2)

# Read JSON from file
with open("data.json", "r") as file:
    loaded_data = json.load(file)
    print("\nLoaded JSON data:")
    print(json.dumps(loaded_data, indent=2))

# 5. CSV file operations
# Write CSV
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "Grade"])
    writer.writerow(["Alice", 20, "A"])
    writer.writerow(["Bob", 22, "B"])
    writer.writerow(["Charlie", 21, "A+"])

# Read CSV
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    print("\nCSV content:")
    for row in reader:
        print(row)

# 6. Using pathlib for file operations
from pathlib import Path

# Create a directory structure
data_dir = Path("data")
data_dir.mkdir(exist_ok=True)

# Create and write to file using pathlib
sample_file = data_dir / "sample.txt"
sample_file.write_text("Hello from pathlib!")

# Read file using pathlib
content = sample_file.read_text()
print(f"\nPathlib content: {content}")

# File operations with pathlib
if sample_file.exists():
    print(f"File size: {sample_file.stat().st_size} bytes")
    print(f"File path: {sample_file.absolute()}")

# 7. Context manager for custom file operations
class FileManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None
    
    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

# Using custom context manager
with FileManager("custom.txt", "w") as file:
    file.write("Custom context manager example!")

# 8. Working with temporary files
import tempfile

# Create temporary file
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
    temp_file.write("This is temporary data")
    temp_path = temp_file.name

print(f"\nTemporary file created at: {temp_path}")

# Read temporary file
with open(temp_path, 'r') as file:
    print(f"Temp file content: {file.read()}")

# Clean up (delete=False means we need to delete manually)
os.unlink(temp_path)

# 9. File system operations
# Get current working directory
current_dir = os.getcwd()
print(f"\nCurrent directory: {current_dir}")

# List files in directory
print("Files in current directory:")
for item in os.listdir("."):
    if os.path.isfile(item):
        print(f"  File: {item}")
    elif os.path.isdir(item):
        print(f"  Directory: {item}/")

# Create directory
new_dir = "test_directory"
if not os.path.exists(new_dir):
    os.makedirs(new_dir)
    print(f"Created directory: {new_dir}")

# Remove directory
os.rmdir(new_dir)
print(f"Removed directory: {new_dir}")

# 10. Error handling in file operations
try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("\nFile not found error handled gracefully")

try:
    with open("/protected/file.txt", "w") as file:
        file.write("test")
except PermissionError:
    print("Permission error handled gracefully")

# Clean up created files
files_to_remove = ["example.txt", "binary.bin", "data.json", "students.csv", "custom.txt", "sample.txt"]
for file_path in files_to_remove:
    try:
        os.remove(file_path)
    except FileNotFoundError:
        pass

# Remove data directory
try:
    import shutil
    shutil.rmtree("data")
except FileNotFoundError:
    pass

print("\nFile handling examples completed!")

Tools

Tools frequently paired with this sample

Related

Related sample collections

Related

Related workflows

Tool usage guide

Sample-focused context for search and workflow understanding

Overview

Start with a minimal print, then trace how a mutable list changes. File examples write to disk, so practice in an isolated working directory.

Choose a code card

Cards display and copy code. Select the fragment you need for your Python environment; each card combines several examples rather than one necessarily unattended program.

The three texts passed syntax parsing. That does not establish that every input, path and runtime dependency is available.

Choose a code card
Sample cardWhat to check
Python Hello WorldBasic output and functions
Python Data StructuresLists and other collections
Python File HandlingFile, JSON and CSV operations

Check the environment

The Hello World card also contains input and may wait for a response. The file-handling card uses relative paths and includes writes, appends and modifications.

Copy the fragment you intend to examine; for file exercises, use a temporary directory and check the target path and permissions.

How it works

  1. 1Copy the relevant snippet.
  2. 2Check Python version, input and working directory.
  3. 3Run and compare output or files.

Edge cases & common failures

  • Whole-card execution

    Other snippets may wait for input, depend on files or have side effects.

  • Encoding

    Specify the encoding and paths appropriate to your environment.

Examples

1. Minimal output

How to use

Copy the first print statement from the first card and run it in Python.

Outcome

The console prints Hello, World! without running later interactive code.

2. Trace a list

How to use

Copy the fruits definition and operations through the assignment to fruits[0] from the second card, then print fruits.

Outcome

The result is ["kiwi", "grape", "cherry"]; pop removed orange after it was appended.

3. Inspect a write mode

How to use

In the third card, run only the example.txt block using w in an isolated directory.

Outcome

example.txt contains three text lines; w overwrites an existing file of the same name.

Hub

Infer JSON Schema from Samples and Spreadsheets

Derive a reviewable JSON Schema draft from representative JSON samples or XLSX rows, then inspect types, requiredness, nulls, and outliers before treating it as a contract.

Hub

Self-Hosted Giveaway Widget Review and Embed Handoff

Review giveaway configuration, merchant response samples, contrast and responsive layouts, then hand off identified widget files with browser acceptance evidence.

Home
Tools3212
Workbench
Samples593
Visualizations471
Viewers103
Hubs239
Tags333
Images, Audio & Video657

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance647

Calculators, numerics, date logic, statistics, and finance tools

Design & Color298

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web193

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

Lead Generation Quiz Launch and Contact Handoff
Memorial Drafts: Family Review and Print Handoff
Private Habit Records: Backup, Restore and Sharing Review
Article to X and LinkedIn Drafts: Fact Review and Handoff
Markdown Interactive Deck Review and Offline Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Data Processing

AI Data Normalizer

AI-powered data format normalization tool that intelligently cleans and standardizes messy data using advanced AI analysis

AI

AI Token Estimator

Analyze language mix and estimate token usage across OpenAI, Codex, Claude, and DeepSeek profiles

Data Processing

CSV Filter

Filter CSV data by column values with multiple conditions and operators. Supports 12 filter operators including equals, contains, greater_than, less_than, and empty value checks. Additional Filters examples: [{"column": "age", "operator": "greater_than", "value": "25"}] [{"column": "status", "operator": "equals", "value": "active"}, {"column": "score", "operator": "greater_equal", "value": "80"}] [{"column": "name", "operator": "contains", "value": "john"}, {"column": "email", "operator": "is_not_empty"}]

Security

CSV/JSON Data Watermarker

Inject visible or signature-style watermark fields into CSV or JSON exports so shared datasets can be traced later

Data Processing

CSV to Database Migration Planner

Infer a relational schema from CSV data and generate create-table plus ALTER migration plans for PostgreSQL, MySQL, SQLite, or SQL Server

Format Conversion

CSV to JSON Converter

Convert CSV data to JSON format with customizable parsing options

Data Processing

CSV Transformer

Transform and process CSV data with column operations, calculations, and data type conversions. Supports renaming columns, adding calculated columns, removing columns, converting data types, calculating values, and filtering rows. Operation examples: • Rename column: [{"type": "rename", "column": "old_name", "new_name": "new_name"}] • Add calculated column: [{"type": "add_column", "new_column": "total", "formula": "price * quantity"}] • Remove column: [{"type": "remove_column", "remove_column": "column_to_remove"}] • Convert data type: [{"type": "convert_type", "convert_column": "age", "target_type": "number"}] • Calculate values: [{"type": "calculate", "target_column": "total", "expression": "price * tax + shipping"}] • Filter rows: [{"type": "filter_values", "filter_column": "status", "operator": "equals", "value": "active"}]

Data Processing

Data Normalizer

Pure code-based data format normalization tool that cleans and standardizes messy data using programmatic logic

Data

CSV Samples

Sample CSV files with various data types, sizes, and complexity levels

Document

PDF Samples

Generated PDF samples from tools dated 2026-02-01 to 2026-02-10

Media

QR Code Samples

Sample QR code images for testing QR code reading and generation tools

Observability

Distributed Tracing Samples

Comprehensive distributed tracing examples using Jaeger, OpenTelemetry, and other modern observability tools for microservices architecture

DevOps

ELK Stack Log Analysis Samples

Comprehensive ELK Stack (Elasticsearch, Logstash, Kibana) samples for log aggregation, processing, and visualization in distributed systems

Cloud Services

AWS EventBridge Samples

AWS EventBridge examples including event buses, rules, targets, schema registry, custom events, and cross-account event routing for serverless event-driven architecture