Python Lists


A list is a mutable, ordered collection of elements enclosed in square brackets [].

  • can store heterogeneous data types
  • support indexing, slicing, and various operations
  • e.g., my_list = [1, 2, 3, 'four', 5.0]
  • Key features:
    1. Mutable
      • elements can be modified, added, or removed
    2. Ordered
      • elements maintain their order
    3. Indexing and Slicing
      • access elements by index or extract sublists
    4. Dynamic
      • size can change during runtime
    5. Common operations
      • append, extend, remove, and more

Uses

  • network automation for managing and processing data related to network devices

Device Information Storage

  • store information about network devices, such as IP addresses, hostnames, and device types
devices = [
    {"hostname": "router1", "ip": "192.168.1.1", "type": "router"},
    {"hostname": "switch1", "ip": "192.168.1.2", "type": "switch"},
    # ...
]

Configuration Templates

  • Maintain lists for configuration templates that can be applied to multiple devices
interface_configs = [
    "interface GigabitEthernet0/1\n",
    " description Connected to Server\n",
    " ip address 192.168.1.1 255.255.255.0\n"
]

Automated Tasks

  • Use lists to iterate over devices and perform automated tasks, such as collecting data or applying configurations
for device in devices:
    connect_to_device(device["ip"])
    collect_device_info(device)
    apply_config_template(device, interface_configs)

Error Handling

  • Maintain lists to track devices that encounter errors during automation tasks
devices_with_errors = []
for device in devices:
    try:
        # Perform automation tasks
    except Exception as e:
        devices_with_errors.append(device)
        log_error(e)

Result Storage

  • Use lists to store the results of operations or commands executed on network devices
command_results = []
for device in devices:
    result = execute_command(device, "show interfaces")
    command_results.append({"device": device["hostname"], "result": result})

List Constructor

A list constructor is a way to create a new list.

  • uses
    • to initialize a list with predefined values
    • to convert an iterable (e.g., a string, tuple, or another list) into a list

The list() constructor takes an iterable as an argument and returns a new list containing the elements of that iterable.

Example: Using a List Constructor in Network Automation

Suppose you have a list of device hostnames in a comma-separated string, and you want to convert it into a list for further processing.

# Example: Using list constructor in network automation

device_names_string = “router1,switch1,firewall1,router2,switch2”

Convert comma-separated string to a list

device_names_list = list(device_names_string.split(’,‘))

Resulting list

print(device_names_list)

Accessing List Items

  •  item indexes represent the position of an element in the list
  • is 0-based, meaning the first element has index 0
  • Negative indexes count from the end, with -1 referring to the last element
  • Access elements using square brackets []
my_list = ['apple', 'banana', 'orange']
 
first_item = my_list[0]       # 'apple' (first element)
second_item = my_list[1]      # 'banana' (second element)
last_item = my_list[-1]        # 'orange' (last element)

Range of Indexes (Slicing)

The concept of range of indexes is used to access a subset of elements from a list, tuple, or string.

  • aka slicing
  • Syntax: sequence[start:stop:step]
    • start is the index where the slice starts (inclusive)
    • stop is the index where the slice ends (exclusive)
    • step is the interval between each index for slicing
  • can use negative indexes to slice from the end
    • e.g., list[-3:] starts at the 3rd from last to the end of list

Searching a List

The in keyword is used to check if a specified item is present in a list, tuple, string, or other iterable object.

  • returns True or False
ip_addresses = ["192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4", "192.168.1.5"]
search_ip = "192.168.1.3"
# Check if the IP address is in the list
ip_present = search_ip in ip_addresses
print(ip_present)  # Output: True

Return Index of Item in a List

  • use the index("item") method on a list
list = ["this", "is", "a", "list"]
myIndex = list.index("is")
# should get 1

Modifying Lists

Changing a List Item

  • The value of a specific item in a list can be changed by referring to the index of the item
  • Syntax is list[index] = new_value

Change a Range of Items in a List

  • Syntax is list[start:stop] = new_values, where new_values is a list of new values

Inserting an Item into a List

The insert() method is used to add an item at a specific position in a list.

  • Syntax is list.insert(index, element)
    • where index is the position in the list where the new element should be inserted

Add List Items

The append() method is used to add an item to the end of a list.

  • Syntax: list.append(element)
    • element is the item to be added

Extend List

 The extend() method is used to add multiple items to the end of a list.
 - Syntax: list.extend(iterable)
 - iterable can be a list, tuple, string, or any iterable object

  • basically appending multiple items

Removing List Items

The remove() method is used to remove the first occurrence of a specified item from a list.

  • Syntax: list.remove(element)
    • element is the item to be removed

Remove a Specified Index

 The pop() method is used to remove an item at a specified position in a list and return it.
 - Syntax: list.pop(index)

  • can store the item in a variable for later use since it is returned

del Keyword

The del keyword is used to delete objects.

  • for lists, can be used to remove an item at a specific position, or to delete a slice of a list
  • Syntax:
    • del list[index]
    • del list[start:stop]

Clear a List

The clear() method is used to remove all items from a list.

  • Syntax: list.clear()

Sorting Lists

The sort() method is used to sort the items in a list in ascending order.

  • Syntax: list.sort()
  • optional key parameter can be provided to specify a function of one argument that is used to extract a comparison key from each element
  • modifies the list it is called on
  • does not work on lists that contain both string and numeric data
  • only works on lists

Example

ip_addresses = ["192.168.1.3", "192.168.1.1", "192.168.1.2"]
# Sort the IP addresses
ip_addresses.sort(key=lambda ip: tuple(map(int, ip.split('.'))))
print(ip_addresses)  # Output: ['192.168.1.1', '192.168.1.2', '192.168.1.3']
  • IP addresses are sorted in ascending order
  • key parameter is used with a lambda function that splits each IP address at the ‘.’ and converts each part to an integer
    •  ensures that the IP addresses are sorted numerically rather than lexicographically
  • To keep the original list in tact, use the sorted() function instead

Sort Descending

The reverse=True keyword argument is used with the sort() method or the sorted() function to sort the items in a list in descending order.

Case-Insensitive Sorts

A case-insensitive sort can be performed by using the sort() method or the sorted() function with a key parameter.

  • key parameter is set to a function that converts each item to lowercase before comparison
    • use built-in str.lower function
device_names = ["Switch1", "router2", "Firewall3", "switch4"]
# Perform a case-insensitive sort
device_names.sort(key=str.lower)
print(device_names)  # Output: ['Firewall3', 'router2', 'Switch1', 'switch4']

Reversing Order of a List

The reverse() method is used to reverse the order of items in a list.

  • Syntax: list.reverse()
  • modifies original list
  • does not return a value
  • only works on lists

Custom Sorts

 The sort() method and the sorted() function can be customized using the key parameter.

The key parameter provides a powerful way to customize the sorting process.

  • can be used with any function that takes one argument and returns a value
  • expects a function that defines the sorting criteria
    • function is applied to each element in a list
    • elements are sorted based on the values returned by this function
  • works with any list element data types
  • only works on lists
  • good practice to use the key parameter when the sorting criteria are more complex than the default comparison of elements
  • only affects the sorting process
    • does not change the original elements in the list

Example

  • the sort() method is customized to sort a list of tuples representing network devices
  • Each tuple contains the device name and its uptime in days
  • The list is sorted based on the uptime:
devices = [("Switch1", 20), ("Router2", 15), ("Firewall3", 30), ("Switch4", 25)]
# Sort the devices based on their uptime
devices.sort(key=lambda device: device[1])
print(devices)  # Output: [('Router2', 15), ('Switch1', 20), ('Switch4', 25), ('Firewall3', 30)]
  • key parameter is used with a lambda function that returns the second element of each tuple (the uptime)
    • ensures that the devices are sorted based on their uptime

Copying a List

  • a list can be copied using several methods
  • Two common ways:
    • Using the copy() method
      • This method creates a new list by copying the original list
      • e.g., copied_list = list.copy()
    • Using the list() constructor
      • This function creates a new list from the original list
      • e.g., copied_list = list(original_list)
  • known as creating a shallow copy of the list
  • a deep copy is used for more complex scenarios involving nested lists or mutable elements
    • using the copy.deepcopy() function

Concatenating Lists

  • Lists can be concatenated using:
    • the + operator
      • combines two lists into a new list
      • e.g., concatenated_list = list1 + list2
    • or the extend() method
      • adds the elements of the second list to the end of the first list
      • modifies the original list
      • e.g., list1.extend(list2)