Skip to content

Lists

Define a list and access specific items

Lists are a collection of ordered items. They are mutable, which means that you can change the items in a list. Lists are defined by square brackets [] and items are separated by commas.

Define a list
switches = ['sw1', 'sw2', 'sw3', 'sw4']

You can access the items in a list by using the index of the item. The index starts at 0.

Access the first item in the list
print(switches[0])
Output
sw1
Access the last item in the list
print(switches[-1])
Output
sw4

So in fact the index is circular, and you can move both ways around that circle. Negative indices as well as positive indices are valid. If you move backwards in a circle from position 0 (to minus 1), you will end up at the last item in the list.

Now that we know the basics of strings and lists, how do we go from one to the other?

Splitting a string into a list

You can split a string into a list using the split() method. The split() method takes a delimiter as an argument and returns a list of strings. Being a method you have to call it on a string object. Its sibling method splitlines() is used to split a multiline string into a list of strings. It is the equivalent of calling split('\n').

Sometimes multiline string start with an empty line, for readability. To get rid of it, use the strip() method. The strip() method removes leading and trailing whitespace from a string.

raw_output = """
FastEthernet1/11
GigabitEthernet0/1/23
Ethernet0/2
"""
# strip() removes leading and trailing whitespace
stripped = raw_output.strip()

# type() of interfaces is list() - the raw_output remains a str() type.
interfaces = stripped.splitlines()

# print the list
print(interfaces)
Output
['FastEthernet1/11', 'GigabitEthernet0/1/23', 'Ethernet0/2']

Let us assume for a moment you've been handed a comma-separated set of values in a csv or text file, and you need to do something useful with it, like automating the configuration of a network device.

Whether you load the contents from a file - or simply copy-paste it into a terminal or IDE - you can split it into a list using the split() method.

Working with comma-separated data
csv_contents = """
Ethernet0/1,192.168.22.254,/24
Ethernet0/2,192.168.44.253,/30
"""
# split on newlines - after stripping.
configuration = csv_contents.strip().split("\n")

# each config line is split again into two lists
eth_a = configuration[0].split(",")
eth_b = configuration[1].split(",")

# print one of the lists:
print(eth_a)
Output
['Ethernet0/1', '192.168.22.254', '/24']

But why aren't we using a loop?

Some may argue that we could have used a loop to iterate over the list of interfaces. They may be right, but as we are just starting out, we'll keep it simple, and get to know what we can do with lists, before we dive into loops.

Joining a list into a string using a delimiter or f-strings

Continuing on our code from above, we can join the list of interfaces into a string using the join() method. The join() method takes a list of strings and returns a single string. You call the join() method on the delimiter that you want to use to join the strings. The insert() method is used to insert an item at a specific position in a list. Let's try them together, to create a configuration for a network device.

Inserting values into a list
eth_a.insert(0, "interface ")
eth_a.insert(2, "\n")
eth_a.insert(3, "  ip address ")
print(eth_a)
Output
['interface ', 'Ethernet0/1', '\n', '  ip address ', '192.168.22.254', '/24']
Using join to convert a list into a string
eth_a_config = "".join(eth_a)
print(eth_a_config)
Output
interface Ethernet0/1
  ip address 192.168.22.254/24

Here we have a perhaps more easily readable example. We use a multiline f-string to create a configuration for a network device.

config for NX-OS
config = f"""
!
interface {eth_a[0]}
  ip address {eth_a[1]}{eth_a[2]}
!
interface {eth_b[0]}
  ip address {eth_b[1]}{eth_b[2]}
!
"""

print(config)
Output
!
interface Ethernet0/1
  ip address 192.168.22.254/24
!
interface Ethernet0/2
  ip address 192.168.44.253/30
!

TASK: Split an interface name and save each part as a separate variable

  • Use the split() method to split the interface name into three parts. chassis, module, and port.
  • Split this string "TwentyFiveGigabitEthernet1/7/2" (1)
  • Print the variables chassis, module, and port separately.
  • Cast the variables to integers if needed.
  • Build a new string (perhaps an IP address?) using the variables.
  1. The string is a Cisco IOS XR interface name. The format is PortType chassis/module/port.
    • chassis in the example is 1
    • module in the example is 7
    • port in the example is 2

EXTRA: Make an interface splitter that works with all cisco ethernet interfaces

  • Print the variables chassis, module, and port separately. (1)
  • Use starred expression in your split() method to split the string into three parts. (2)
  • Build a new string using the variables, possibly using the join()(3) method and starred expression.(4)
  • Cast the variables to integers if needed.
  • These strings should work:
    "GigabitEthernet1/0/1"
    "TwentyFiveGigabitEthernet1/7/2"
    "FortyGigabitEthernet0/0"
  1. Unpack the list into the variables. This can simply be done with the following code:
parts = "1,2,3".split(",")
a, b, c = parts
  1. The starred expression is used to unpack a list of variable length into the variables.
*a, b, c = "1,2,3".split(",")
print(a, b, c)
['1'] 2 3
*a, b, c = "2,3".split(",")
print(a, b, c)
[] 2 3
  1. Reconstruct the original string using list methods like this:
numbers = []
numbers.extend(a)
numbers.append(b)
numbers.append(c)
print("/".join(numbers))
  1. Reconstruct the original string using starred expression like this:
numbers = [*a, b, c]
string = "/".join(numbers)
print(string)

Congratulations! You have now learned how to work with lists in Python. There are many other use-cases and methods for lists, but these are some of the basics.

We will cover more advanced topics in the future as we continue to build on our Python skills. Lists are especially useful in loops, so they shall make a grand return in a future lesson.