Lesson Contents
A Python list is, as the name implies, a list of items. A list can be an alternative to using multiple variables.
Let’s say I want to use the IP addresses of different devices in my Python program. I could create a new variable for each and assign a string:
It might be easier, however, to use a list. Here’s an example:
Above, we have a list with strings but you can add almost everything in a list. For example, numbers:
Even a combination of strings and numbers is possible:
Access items in list
I can access items in the list by adding the index number between brackets []. For example:
Python starts counting from 0, that’s the first item in the list.
I can also start from the last item in the list by supplying a negative number. The item on the far right has index number -1. Here is an example:
Adding or removing items in list
We can also add or remove items from our list.
Add item
We can add an item to our list with append. Here’s an example:
We successfully added another IP address to our list.
Remove item by index number
How about removing an item from our list? We can do this with the popmethod. Let’s remove the first item:
The first item on our list is now gone.
Remove item by name
We can also remove an item by name. Here is an example:
Nested Lists
We have seen that we can add strings and numbers to a list, but you can also add a list to a list. Here is an example:
The new “routers_switches” list contains our two existing lists.
Concatenate lists
It’s also possible to combine (concatenate) two lists into a new list. Here’s how:
Our “all_ip_addresses” list contains the content of both existing lists.
List Functions
There are some useful functions we can use on our lists. Let’s walk through them.
Len
We can retrieve the number of items in the list with the len function:
Min and Max
We can retrieve the highest or lowest value of a list. This works with integers in a list:
It also works with strings in a list that you want to sort alphabetically:
I think there is a mistake for the Len function it is a copy of the Concatenate function. Also. thanks so much for the lesson!
Hello Justin
Yes, you are correct, thanks for pointing that out. I will let Rene know to make the appropriate changes.
Laz
Thanks @Jallen.jaxit, I fixed this.
Rene
Hello Amina
Taking a look at this section of the lesson, I see that the code is displayed correctly:
https://cdn-forum.networklessons.com/uploads/default/original/2X/1/1cf7fca6c1a08843162d37b92da83481763ef524.png
Can you let us know under what circumstances you can’t see it so that we can fix it if there is a problem?
Thanks!
Laz