The previous day went over the basics of the Python List. On this day I go a little further into List Methods.
List Methods allow you to work with the items within a List. With methods such as removing and sorting. Useful methods when working with a list at any capacity.
There’s going to be a time where you need to remove a value from a list. It’s possible to do it with the
wifi = ['rssi', 'snr', 'spatial streams'] wifi ['rssi', 'snr', 'spatial streams'] del wifi wifi ['snr', 'spatial streams']
But it is possible to do it with the remove method as well:
wifi = ['rssi', 'snr', 'spatial streams'] wifi.remove('rssi') wifi ['snr', 'spatial streams']
The difference is the remove method uses parenthesis with the actual name of the item within the list. It’s easier to call out the actual name than the index number within the list.
But what happens if the item isn’t in the list? A ValueError occurs:
wifi.remove('antenna') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.remove(x): x not in list
Let’s say I have a list of Tweeps and I want to sort it alphabetically.
tweeps = ['françois', 'robert', 'sam', 'keith', 'alex'] tweeps ['françois', 'robert', 'sam', 'keith', 'alex'] tweeps.sort() tweeps ['alex', 'françois', 'keith', 'robert', 'sam']
Good stuff. It also works with numbers.
ages = [54, 92, 65, 27, 3] ages.sort() ages [3, 27, 54, 65, 92]
What a list is not capable of sorting is a mix of integers and strings. You end up with a TypeError:
mix = ['spam', 'rice', 3, 5, 'red'] mix.sort() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '<' not supported between instances of 'int' and 'str'
I’m sure in networking there will be many reasons to use a list. I can just see it happening but I don’t have any specific use case as of yet. It’s still early for me to figure out what I’d be using a list for. Maybe a list of IP addresses or interfaces of a switch or router.