Python Lists
Lists
Python lists are a collection of data, which can be stored as a variable, manipulated and extracted from or added to. As we will see in the next examples. Let’s start with a simple list, where we store hostnames for 4 routers, R1, R2, R3 and R4.
My_nodes = ["R1", "R2", "R3", "R4"]
print (My_nodes)
#Output will be:
['R1', 'R2', 'R3', 'R4']
NOTE:
Lists items order start with zero, one, two. and so on. |
---|
If I want to print or see the 3rd item in my list, I simply print item 2.
My_nodes = ["R1", "R2", "R3", "R4"]
print(My_nodes[2])
#
output will be:
R3
You can also print a range with this syntax [x;y]. This will show items in position x, all the way to y…but not including y. See example below:
My_nodes = ["R1", "R2", "R3", "R4"]
print(My_nodes[1:3])
#Output will be:
['R2', 'R3']
Append & pop
Appending allow us to add to the list, whereas pop does just the opposite. Let’s look at below examples and output.
#original list
My_nodes = ["R1", "R2", "R3", "R4"]
#add R5 to the list
My_nodes.append("R5")
print (My_nodes)
#output is:
['R1', 'R2', 'R3', 'R4', 'R5']
When it comes to “pop”, I can pop the last time when none is specified. Or, I can remove a specific item by listing the item order.
My_nodes = ["R1", "R2", "R3", "R4"]
My_nodes.pop()
print (My_nodes)
#Print output:
['R1', 'R2', 'R3']
My_nodes = ["R1", "R2", "R3", "R4"]
#pop item list 2, which is R3
My_nodes.pop(2)
print (My_nodes)
#print output:
['R1', 'R2', 'R4']
Count
In this example, I count the number of instances for a given item. How many items “ios” are there in my list My_sw
My_sw = ["ios", "xr", "ios", "ios"]
nodes_count = My_sw.count("ios")
print (nodes_count)
#print output is:
3
Python crash course video
To learn more about Python for Engineers, watch this 1hr crash course video.
This course covers foundation topics: