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 = [1, 2, 3, 4, 5]

Your list could be strings like this:

mylist = ['one', 'two', 'three', 'four', 'five']

You can mix the types of elements like this:

mylist = ['one', 20 , 5.5 , [10, 15], 'five']

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]

 

Mutable lists

Lists are mutable because you change or reorder items after you create it.

If we have a list like the following:

mylist = ['one', 'two', 'three', 'four', 'five']

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:

['one', 'two', 'New item', 'four', 'five']

If the index is a negative number, it counts from the last element.

mylist = ['one', 'two', 'three', 'four', 'five']

elem = mylist[-1]

print(elem)

The output of this code will be:

five

 

Traverse a list

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

mylist = ['one', 'two', 'three', 'four', 'five']

for elem in mylist:

    print(elem)

This way you can read the list elements. What about updating the elements:

mylist = [1, 2, 3, 4, 5]

for i in range(len(mylist)):

    mylist[i]+=5

print(mylist)

The result will be:

[6, 7, 8, 9, 10]

You can use the len() function to return the elements count, while the range() function returns the list of indices.

Keep in mind that, the nested list considered one element, regardless of how many elements inside it.

mylist = ['one', 20 , 5.5 , [10, 15], 'five']

print(len(mylist))

The result of the above code is

5

 

Slice a list

You can slice a list using (:) operator like this:

mylist = ['one', 'two', 'three', 'four', 'five']

print(mylist[1:3])

The result from the above code will be:

['two', 'three']

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 list will be copied.

mylist = ['one', 'two', 'three', 'four', 'five']

print(mylist[1:3])

print(mylist[1:])

print(mylist[:3])

print(mylist[:])

The result of the above code will be:

['two', 'three']

['two', 'three', 'four', 'five']

['one', 'two', 'three']

['one', 'two', 'three', 'four', 'five']

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

mylist = ['one', 'two', 'three', 'four', 'five']

mylist[1:3] = ['Hello', 'Guys']

print(mylist)

The result will be:

['one', 'Hello', 'Guys', 'four', 'five']

 

Insert into a list

You can use the insert method to insert an element to the list like this:

mylist = [1, 2, 3, 4, 5]

mylist.insert(1,'Hello')

print(mylist)

The result will be:

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

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

 

Append to a list

To append an element to a list, you can use the append method like this:

mylist = ['one', 'two', 'three', 'four', 'five']

mylist.append("new one")

print(mylist)

The result will be:

['one', 'two', 'three', 'four', 'five', 'new one']

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

mylist = ['one', 'two', 'three', 'four', 'five']

list2 = ["Hello", "Guys"]

mylist.extend(list2)

print(mylist)

The result will be:

['one', 'two', 'three', 'four', 'five', 'Hello', 'Guys']

Of course, list2 will remain untouched.

 

Sort a list

To sort a list, use the sort method.

mylist = ['cde', 'fgh', 'abc', 'klm', 'opq']

list2 = [3, 5, 2, 4, 1]

mylist.sort()

list2.sort()

print(mylist)

print(list2)

The output will be:

['abc', 'cde', 'fgh', 'klm', 'opq']

[1, 2, 3, 4, 5]

 

Reverse a list

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

mylist = [1, 2, 3, 4, 5]

mylist.reverse()

print(mylist)

The output will be:

[5, 4, 3, 2, 1]

 

Index of an element

You can use the index method to get the element index like this:

mylist = ['one', 'two', 'three', 'four', 'five']

print(mylist.index('two'))

The result will be:

1

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

 

Delete an element

You can delete an element by specifying the element index to the pop method like this:

mylist = ['one', 'two', 'three', 'four', 'five']

removed = mylist.pop(2)

print(mylist)

print(removed)

The result will be:

['one', 'two', 'four', 'five']

three

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

mylist = ['one', 'two', 'three', 'four', 'five']

removed = mylist.pop()

print(mylist)

print(removed)

The result will be:

['one', 'two', 'three', 'four']

five

You can remove an element using remove method like this:

mylist = ['one', 'two', 'three', 'four', 'five']

mylist.remove('two')

print(mylist)

The result will be:

['one', 'three', 'four', 'five']

You can use the del operator to remove an element like this:

mylist = ['one', 'two', 'three', 'four', 'five']

del mylist[2]

print(mylist)

The result will be:

['one', 'two', 'four', 'five']

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

mylist = ['one', 'two', 'three', 'four', 'five']

del mylist[1:3]

print(mylist)

The result will be:

['one', 'four', 'five']

 

Aggregate functions

Python has some built-in aggregate functions like:

mylist = [5, 3, 2, 4, 1]

print(len(mylist))

print(min(mylist))

print(max(mylist))

print(sum(mylist))

The sum() function works on numeric items.

Also, you can use these functions (max(), len(), etc.) to deal with strings.

 

Compare lists

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

mylist = ['one', 'two', 'three', 'four', 'five']

list2 = ['four', 'one', 'two', 'five', 'three']

print(cmp(mylist,list2))

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

You can compare two lists using the == operator in Python 3 like this:

mylist = ['one', 'two', 'three', 'four', 'five']

list2 = ['four', 'one', 'two', 'five', 'three']

if (mylist == list2):

    print("match")

else:

    print("No match")

The result will be:

No match

 

Math operations on lists

You can use the plus (+) to merge lists like this:

list1 = [1, 2, 3]

list2 = [4, 5, 6]

print(list1 + list2)

The output will be:

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

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

list1 = [1, 2, 3]

list2 = [4, 5, 6]

print(list1 * 2)

The result will be:

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

 

Lists and strings

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

mystr = "LikeGeeks"

mylist = list(mystr)

print(mylist)

The result will be:

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

The list function breaks a string into single letters as shown.

You can use the split method to split the text into words like this:

mystr = "Welcome to likegeeks website"

mylist = mystr.split()

print(mylist)

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.

What about using another splitter other than space?

mystr = "Welcome-to-likegeeks-website"

mylist = mystr.split('-')

print(mylist)

The result will be the same as 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 join list elements to make one string using the join method like this:

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

delimiter = ' '

output = delimiter.join(mylist)

print(output)

The output will be:

Welcome to likegeeks website

 

Aliasing

When two variables referencing the same object like this:

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

list2 = mylist

Aliasing means the object has more than one reference with more than one name.

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

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

list2 = mylist

list2[3] = "page"

print(mylist)

The result will be:

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

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

You shouldn’t do aliasing when working with lists.

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.

8 thoughts on “Python List Functions – The Definitive Guide
    1. Thanks a lot.
      I will do my best to make upcoming posts useful and interesting.

  1. index of an element :
    replace ‘second’ with ‘two’
    print(mylist.index(‘second’)) => print(mylist.index(‘two’))

  2. Nice summary. Thanks. I keep forgetting some of these. One strangeness though. Almost everything in this post was a simple imformative statement about the definition of the python language. The one exception was “You shouldn’t do aliasing when working with lists.” That statement is an opinion. More over an opinion which you didn’t bother to justify. It may be good advice but you you will not find it in the python spec. It didn’t really fit with the rest of the post.

Leave a Reply

Your email address will not be published. Required fields are marked *