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.
You can access the items in a list by using the index of the item. The index starts at 0.
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)
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.
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)
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.
eth_a.insert(0, "interface ")
eth_a.insert(2, "\n")
eth_a.insert(3, " ip address ")
print(eth_a)
Here we have a perhaps more easily readable example. We use a multiline f-string to create a configuration for a network device.
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)
!
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, andport. - Split this string
"TwentyFiveGigabitEthernet1/7/2"(1) - Print the variables
chassis,module, andportseparately. - Cast the variables to integers if needed.
- Build a new string (perhaps an IP address?) using the variables.
- The string is a Cisco IOS XR interface name. The format is
PortType chassis/module/port.chassisin the example is1modulein the example is7portin the example is2
EXTRA: Make an interface splitter that works with all cisco ethernet interfaces
- Print the variables
chassis,module, andportseparately. (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"
- Unpack the list into the variables. This can simply be done with the following code:
- The starred expression is used to unpack a list of variable length into the variables.
- Reconstruct the original string using list methods like this:
- Reconstruct the original string using starred expression like this:
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.