📊 Python Training - Day 4

Lists, Tuples, Dictionaries & Data Structures

📝 Quick Quiz (5 Questions)

  1. Lists in Python are:
  2. Tuples are best for:
  3. Dictionaries index by:
  4. Select list method:
  5. Dictionary comprehension creates:
Answer all questions and click Submit.

📋 Lists

List Operations

Lists can store multiple items in a single variable.

devices = ["R11", "R12", "SW110", "SW101", "SW102"] print(devices) # ['R11', 'R12', 'SW110', 'SW101', 'SW102']

List Slices

Extracting parts of a list.

print(devices[1:4]) # ['R12', 'SW110', 'SW101'] print(devices[:3]) # ['R11', 'R12', 'SW110'] print(devices[2:]) # ['SW110', 'SW101', 'SW102']

List Methods

Built-in functions to manipulate lists.

# Add element devices.append("SW103") print(devices) # ['R11', 'R12', 'SW110', 'SW101', 'SW102', 'SW103'] # Remove element devices.remove("SW101") print(devices) # ['R11', 'R12', 'SW110', 'SW102', 'SW103'] # Insert at specific position devices.insert(0, "R10") print(devices) # ['R10', 'R11', 'R12', 'SW110', 'SW102', 'SW103']

Mutability

Lists can be changed after their creation.

devices[0] = "Router1" print(devices) # ['Router1', 'R12', 'SW110', 'SW102', 'SW103']

Aliasing and Cloning

Aliasing refers to referencing the same list with different names, while cloning creates a copy.

# Aliasing Example devices_alias = devices devices_alias[0] = "R11_Alias" print(devices) # ['R11_Alias', 'R12', 'SW110', 'SW102', 'SW103'] # Cloning devices_clone = devices[:] devices_clone[0] = "R11_Clone" print(devices) # ['R11_Alias', 'R12', 'SW110', 'SW102', 'SW103'] print(devices_clone) # ['R11_Clone', 'R12', 'SW110', 'SW102', 'SW103']

List Comprehension

A concise way to create lists.

device_status = ["up" if device.startswith("R") else "down" for device in devices] print(device_status) # ['up', 'up', 'down', 'down', 'down']

🔗 Tuples

Tuple Assignment

Assigning multiple values to a tuple.

ip_tuple = ("192.168.1.1", "192.168.1.2", "192.168.1.3") print(ip_tuple) # ('192.168.1.1', '192.168.1.2', '192.168.1.3')

Tuple as Return Value

Returning multiple values from a function as a tuple.

def get_device_info(device_name): return device_name, "Active", 48 name, status, ports = get_device_info("SW101") print(f"Device: {name}, Status: {status}, Ports: {ports}")

Tuple Comprehension

Tuples do not have comprehensions, but you can generate tuples from lists.

devices_tuple = tuple(devices) print(devices_tuple) # ('R11_Alias', 'R12', 'SW110', 'SW102', 'SW103')

📚 Dictionaries

Operations and Methods

Dictionaries store data in key-value pairs.

# Create dictionary device_config = { "SW101": {"status": "up", "ports": 48, "uptime": "99.9%"}, "SW102": {"status": "up", "ports": 48, "uptime": "99.8%"}, "SW110": {"status": "down", "ports": 24, "uptime": "95.2%"} } # Access values print(device_config["SW101"]["status"]) # up # Add new device device_config["SW103"] = {"status": "up", "ports": 48, "uptime": "99.9%"} # Update values device_config["SW101"]["uptime"] = "100%" # Remove device del device_config["SW110"]

Dictionary Methods

# Get all keys print(device_config.keys()) # dict_keys(['SW101', 'SW102', 'SW103']) # Get all values print(device_config.values()) # Get all items print(device_config.items()) # Check if key exists if "SW101" in device_config: print("SW101 is configured") # Get value with default status = device_config.get("SW999", "Not found") print(status) # Not found

Dictionary Comprehension

A concise way to create dictionaries.

device_status = {device: "up" if device.startswith("R") else "down" for device in devices} print(device_status) # {'R11_Alias': 'up', 'R12': 'up', 'SW110': 'down', 'SW102': 'down', 'SW103': 'down'}

📊 Data Structure Comparison

Feature Lists Tuples Dictionaries
Mutability Mutable (can be changed) Immutable (cannot be changed) Mutable (can be changed)
Order Ordered Ordered Ordered (Python 3.7+)
Indexing Integer indices Integer indices Key-based indexing
Duplicates Allowed Allowed Keys must be unique
Use Case Ordered collection of items Fixed collection of items Key-value mappings

🎮 Interactive Demo: Data Structure Practice

Try different data structure operations:

List Operations

List: []

Tuple Operations

Tuple: ()

Dictionary Operations

Dictionary: {}

🔧 Network Automation Scripts

Using Lists, Tuples, and Dictionaries

def automate_ip_configuration(): """Automate IP configuration using data structures""" # List of devices devices = ["SW101", "SW102", "SW110"] # Tuple of IP configurations ip_configs = ( ("192.168.1.1", "255.255.255.0"), ("192.168.1.2", "255.255.255.0"), ("192.168.1.3", "255.255.255.0") ) # Dictionary for device status device_status = {} # Configure each device for i, device in enumerate(devices): ip, subnet = ip_configs[i] device_status[device] = { "ip": ip, "subnet": subnet, "status": "configured" } print(f"Configured {device}: {ip}/{subnet}") return device_status # Run the automation config = automate_ip_configuration() print(f"\\nConfiguration complete: {config}")

✨ List Comprehensions Deep Dive

Advanced List Comprehensions

# Basic list comprehension devices = ["SW101", "SW102", "SW110", "R101", "R102"] router_devices = [device for device in devices if device.startswith("R")] print(router_devices) # ['R101', 'R102'] # List comprehension with conditions device_status = ["up" if device.startswith("R") else "down" for device in devices] print(device_status) # ['down', 'down', 'down', 'up', 'up'] # Nested list comprehension network_topology = [ [f"{device}-port-{port}" for port in range(1, 5)] for device in devices[:2] ] print(network_topology) # [['SW101-port-1', 'SW101-port-2', 'SW101-port-3', 'SW101-port-4'], # ['SW102-port-1', 'SW102-port-2', 'SW102-port-3', 'SW102-port-4']]

🎮 Interactive Demo: Complete Network Management

Run the complete network management script:

Click a button to see the network management scripts in action!

📚 Summary

This guide covers essential Python concepts of lists, tuples, and dictionaries with practical examples related to network automation.

Key Concepts Covered:

  • Lists: Mutable, ordered collections with various methods
  • Tuples: Immutable, ordered collections for fixed data
  • Dictionaries: Key-value mappings for structured data
  • Comprehensions: Concise ways to create data structures

Best Practices:

  • Use lists for ordered, mutable collections
  • Use tuples for fixed, immutable data
  • Use dictionaries for key-value mappings
  • Leverage comprehensions for clean, readable code

▶️ Run the code (Python in your browser)

Execute Python below using Pyodide. Edit the code and click Run.

Initializing Python runtime...

🎥 Video Lesson

© NexIQ AI Automation Pvt Ltd | https://nexiq.netlify.app/ | hr@nexiq.in