Python List Functions
Python

Python List Functions – The Definitive Guide

Python list is a sequence of values, it can be any type, strings, numbers, floats, mixed content, or whatever. In this post, we will talk about Python list functions and how to create, add elements, append, reverse, and many other Python list functions.

 

Create Python Lists

To create a python list, enclose your elements in square brackets like this:

mylist = [10, 20, 30, 40, 50]

You can make a list of strings like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

The elements of a list don’t have to be the same type. You can mix them like this:

mylist = ['first', 20 , 5.5 , [10, 15], 'fifth']

You can write nested lists, which means lists inside lists live the above example.

Also, you can access any element of the list by its index which is zero based.

third_elem = mylist[2]

List indices work the same way as string indices. You can review the Python programming basics post.

Mutable Lists

Lists are mutable because items can be changed or reordered.

If we have a list like the following:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

We can change the third item like this:

mylist[2] = "New item"

Now if you print the list, you should see the new list like this:

['first', 'second', 'New item', 'fourth', 'fifth']

If the element you need to read or write does not exist, you get an IndexError.

If the index is a negative number, it counts from the end of the list.

The output of this code will be: fifth

Traverse a List

You can traverse the elements of a list using a for loop like this:

This works great if you want to read the elements of the list. What about updating the elements:

The result will be:

[6, 7, 8, 9, 10]

The len() function is used to return the number of elements in the list, while the range() function returns the list of indices.

Keep in mind that, the nested list still counts as a single element, regardless of how many elements inside it.

The result of the above code is 5

Slice a List

The slice operator also works on lists like this:

The result from the above code will be ['second', 'third']

If you remove the first number, the items start from the beginning. If you remove the second number, the items go to the end.

If you remove both numbers and remain the colon, the slice is a copy of the whole list.

The result of the above code will be:

Since lists are mutable, you can change elements using the slice operator:

The result will be:

['first', 'Hello', 'Guys', 'fourth', 'fifth']

Insert Into a List

You can insert a new element to the list using the insert method like this:

The result will be:

[1, 'Hello', 2, 3, 4, 5]

Also, the index of the inserted element is zero based.

Append to a List

You can add a new element to the end of a list using the append method like this:

The result will be:

['first', 'second', 'third', 'fourth', 'fifth', 'new one']

You can append more than one element using extend method like this:

The result will be:

['first', 'second', 'third', 'fourth', 'fifth', 'Hello', 'Guys']

Of course, list2 will remain untouched.

Sort a List

The sort method sorts the elements of the list from low to high.

The output will be:

Reverse a List

You can reverse the order of a Python list using the reverse method like this:

The output will be:

[5, 4, 3, 2, 1]

Index of an element

You can get the index of an element using the index method like this:

The result will be:

1

If you have more than one element with the same name supplied to index function, it will return the first index that matches the supplied value.

Delete an Element

If you have the index of the element you want to delete, you can use the pop method like this:

The result will be:

If you don’t specify an index for the pop method, it will delete the last element.

The result will be:

If you don’t know the index of the element, but you know the element itself, you can remove it using remove method like this:

The result will be:

['first', 'third', 'fourth', 'fifth']

If you don’t need the removed value, you can use the del operator like this:

The result will be:

['first', 'second', 'fourth', 'fifth']

Also, you can delete multiple elements using slice operator like this:

The result will be:

['first', 'fourth', 'fifth']

Aggregate Functions

There are a number of built-in aggregate functions that can be used on lists that allow you to go through the list without writing a loop for that.

The sum() function works on numeric items.

Also, you can use these functions (max(), len(), etc.) to deal with lists of strings and other comparable types.

Compare Lists

If you are using python 2, you can compare elements of two lists using the cmp function like this:

It will return -1 if no match, or it will return 1 if it matches.

If you are using python 3, you can compare two lists using the == operator like this:

The result will be:

No match

List Operations

The + operator concatenates lists like this:

The output will be:

[1, 2, 3, 4, 5, 6]

Also, you can repeat a list using the multiply operator like this:

The result will be:

[1, 2, 3, 1, 2, 3]

Lists and Strings

To convert a string to a list of characters, you can use the list function like this:

The result will be:

['L', 'i', 'k', 'e', 'G', 'e', 'e', 'k', 's']

The list function is used to break a string into single letters as shown.

To break a string into words, use the split method:

The result will be:

['Welcome', 'to', 'likegeeks', 'website']

As you see, the returned output is a normal list, you can get any word by index and manipulate it.

Also, you can specify a delimiter for the split method, so instead of the default delimiter which is the space, you can supply another one.

The result will be the same like the above example:

['Welcome', 'to', 'likegeeks', 'website']

Join a List

The opposite process of splitting a string to a list of strings is to join them to make a string.

You can concatenate a list of strings to make a string using the join method like this:

The output will be:

Welcome to likegeeks website

Aliasing

When two variables referencing the same object like this:

When we say that the object is aliased, that means the object has more than one reference with more than one name.

Look at the following example to understand how mutable lists change:

The result will be:

['Welcome', 'to', 'likegeeks', 'page']

We made a change to list2, but since they are referencing to the same object and that object is mutable, the changes affect the original list.

When you are working with mutable objects like lists, you shouldn’t do aliasing.

It can be useful and it can be a source of errors, so be careful when working with mutable objects when they are aliased.

Working with a python list is very easy as we’ve seen. I hope you find the post useful and interesting. Keep coming back.

Thank you.

  • winprg

    Useful page, especially deleting from list:
    del d[a:b] and d.pop() and d.remove().

    • Thanks a lot.
      I will do my best to make upcoming posts useful and interesting.