Tag Archives: Automation

Sorting list in Python

During my Python studies, I came across something that didn’t make much sense to me so I had to learn and investigate (with the help of experts).

What you can usually do in Python is to modify a variable and assign the result to the same variable. Because a piece of code is usually worth much more than an explanation:

When you want to sort a list, that behavior is a bit different:

let’s pretend I have a list of ARP entries into my switch:

If I want to sort it and reassign the value of it to the previously used variable I would use this code (Let’s pretend arp_entries is my variable that contains all these entries):

According to this python official documentation, Python lists have a built-in list.sort() method that modifies the list in place. Let’s verify this:

There is also a sorted list function that can do the job if you want to keep the original list intact:

I was testing this because I am currently working on the free python class that is run by Kirk Byers at https://pynet.twb-tech.com/ . To make the most of this course, I strongly recommend that course if you have a very small experience of programming. I will talk about that in a next blog post but in the meantime, have a look at kirk’s website. It’s awesome!

Thanks to Kirk, Nicholas Russo and Greg Mueller for the hints and help provided on slack ( Network to Code ran by Jason Edelman )