Python Lists

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:

Unlock This Lesson for Free - No Payment Required!

If you like to keep on reading, register now!

  • Learn CCNA, CCNP and CCIE R&S. Explained As Simple As Possible.
  • Get Instant Access to this Full Lesson, Completely for Free!
  • Unlock More to Read. More Lessons Added Every Week!
  • Content created by Rene Molenaar (CCIE #41726)
2527 Sign Ups in the last 30 days

Forum Replies

  1. 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!

  2. Hello Justin

    Yes, you are correct, thanks for pointing that out. I will let Rene know to make the appropriate changes.

    Laz

  3. Thanks @Jallen.jaxit, I fixed this.

    Rene

2 more replies! Ask a question or join the discussion by visiting our Community Forum