Python List Functions – Tutorial With Examples

This tutorial explains some useful Python List Functions with the help of syntax and programming examples:

Though lists have methods that act on its object directly, Python has built-in functions that create and manipulate lists in-place and out-of-place.

Most of the functions we shall cover in this tutorial will apply to all sequences, including tuples and strings, but we shall focus on how these functions apply on list under certain topics.

=> Check ALL Python Tutorials Here

Python List Built-in Functions

Python List Functions

Given below are some important Python list built-in functions. Kindly visit the Python official documentation page for details of these functions.

Commonly Used Python List Built-in Functions

NameSyntaxDescription
lenlen(s)Returns the number of element in the list .
listlist([iterable])Creates a list out of an iterable.
rangerange([start,]stop[,step])Returns an iterator of integers from start to stop, with an increment of step.
sumsum(iterable[,start])Adds all items of an iterable.
minmin(iterable[,key, default])Gets the smallest item in a sequence.
maxmax(iterable[,key, default])Gets the largest item in a sequence.
sortedsorted(iterable[,key,reverse])Returns a new list of sorted items in iterable.
reversedreversed(iterator)Reverses an iterator.
enumerateenumerate(sequence, start=0)Returns an enumerate object.
zipzip(*iterables)Returns an iterator that aggregates items from each iterables.
mapmap(function, iterable,...]Returns iterator that applies function to each item of iterables.
filterfilter(function, iterable)Returns an iterator from elements of iterable for which function returns true.
iteriter(object[,sentinel])Converts an iterable into an iterator.

Just like all built-in functions in Python, the list functions are first-class objects and are the functions that create or act on list objects and other sequences.

As we shall see, moving forward, most list functions act on list objects in-place. This is due to a list’s characteristic called mutability, which enables us to modify the lists directly.

We have functions that are commonly used to manipulate lists. For example: len(), sum(), max(), range() and many more. We also have some functions that are not commonly used like any(), all(), etc. However, these functions can help a lot while working with lists if used properly.

Note: Before we move on to the discussion on different list functions, it is worth noting that, in Python we can get a built-in function’s docstring and other helpful details with __doc__ and help(). In the example below, we get the dockstring of the len() function.

>>> len.__doc__
'Return the number of items in a container.'

Commonly Used Python List Functions

In this section, we will discuss some commonly used Python functions and see how they apply to lists.

#1) len()

The Python list method len() returns the size(number of items) of the list by calling the list object’s own length method. It takes in a list object as an argument and doesn’t have a side effect on the list.

Syntax:

len(s)

Where s can be either a sequence or collection.

Example 1: Write a function that computes and returns the size/length of a list.

def get_len(l):
    # Python list function len() computes the size of the list.
    return len(l)

if __name__ == '__main__':
    l1 = []                  # defined an empty list
    l2 = [5,43,6,1]          # define a list of 4 elements
    l3 = [[4,3],[0,1],[3]]   # define a list of 3 elements(lists)

    print("L1 len: ", get_len(l1))
    print("L2 len: ", get_len(l2))
    print("L3 len: ", get_len(l3))

Output

len() - Output

Note: Alternative to using the index -1 to access the last item of a list obj[-1], we can also access the last item of a list with len() as below:

obj[ len(obj)-1]

#2) list()

list() is actually a Python built-in class that creates a list out of an iterable passed as an argument. As it will be used a lot throughout this tutorial, we will take a quick look at what this class offers.

Syntax:

list([iterable])

The bracket tells us that the argument passed to it is optional.

The list() function is mostly used to:

  • Convert other sequences or iterables to a list.
  • Create an empty list – In this case, no argument is given to the function.

Example 2: Convert tuple, dict to list, and create an empty list.

def list_convert():
    t = (4,3,5,0,1)      # define a tuple
    s = 'hello world!'   # define a string
    d = {'name':"Eyong","age":30,"gender":"Male"}  # define a dict
 
    # convert all sequences to list
    t_list, s_list, d_list = list(t), list(s), list(d)
    # create empty list
    empty_list = list()  

    print("tuple_to_list: ", t_list)
    print("string_to_list: ", s_list)
    print("dict_to_list: ", d_list)
    print("empty_list: ", empty_list)
    
    
if __name__ == '__main__':
    list_convert()

Output

list - Output

Note: Converting a dictionary using list(dict) will extract all its keys and create a list. That is why we have the output [‘name’,’age’,’gender’] above. If we want to create a list of a dictionary’s values instead, we’ll have to access the values with dict.values().

#3) range()

The Python list function range() takes in some integers as arguments and generates a list of integers.

Syntax:

range([start,]stop[,step])

Where:

  • start: Specifies where to start generating integers for the list.
  • stop: Specifies where to stop generating integers for the list.
  • step: Specifies the incrementation.

From the syntax above, start and step are both optional and they default to 0 and 1 respectively.

Example 3: Create a sequence of numbers from 4 to 20, but increment by 2 and print it.

def create_seq(start, end, step):
    # create a range object
    r = range(start, end, step)
    # print items in the range object.
    for item in r:
        print(item)


if __name__ == '__main__':
    start = 4  # define our start number
    end = 20   # define out end number
    step = 2   # define out step number

    print("Range of numbers:")
    create_seq(start, end, step)

Output

range - output

Note: Since list() generates a list from an iterable, we can create a list from the range() function.

>>> list(range(4,20,2))
[4, 6, 8, 10, 12, 14, 16, 18]

#4) sum()

The Python sum() function adds all items in an iterable and returns the result.

Syntax:

sum(iterable[,start])

Where:

  • The iterable contains items to be added from left to right.
  • start is a number that will be added to the returned value.

The iterable’s items and start should be numbers. If start is not defined, it defaults to zero(0).

Example 4: Sum items from a list

>>>  sum([9,3,2,5,1,-9])
11

Example 5: Start with 9 and add all items from the list [9,3,2,5,1,-9].

>>> sum([9,3,2,5,1,-9], 9)
20

Note: We can implement the sum() function with the traditional for loop.

def sum_loop(list_items, start):
    total = start  # initialize with start number
    # iterate through the list
    for item in list_items:
        # add item to total
        total += item
    return total

if __name__ == '__main__':
    list_items = [9,3,2,5,1,-9] # define our list
    start = 9 # define our start.
    print("SUM: ", sum_loop(list_items, 9))

Output

sum() - Output

#5) min()

The Python min() function returns the smallest item in a sequence.

Syntax:

min(iterable[,key, default])

Where:

  • iterable here will be a list of items.
  • key here specifies a function of one argument that is used to extract a comparison key from each list element.
  • default here specifies a value that will be returned if the iterable is empty.

Example 6: Find the smallest number in the list [4,3,9,10,33,90].

>>> numbers = [4,3,9,10,33,90]
>>> min(numbers)
3

Example 7: In this example, we shall see key and default in action. We shall find the min of an empty list and the min of a list of integer literals.

The list object numbers contains integer literals. Instead of returning the minimum as a string, we use the key keyword to convert all the items into an integer. Thus the resulting minimum value will be an integer.

The list object empty_list is an empty list. As our list is empty, we shall define a default

Note: If the iterable is empty and default is not provided, a ValueError is raised.

def find_min():
    numbers = ['4','3','9','10','33','90']  # create list of integer literal
    empty_list = []     # create empty list

    print("MIN OF EMPTY LIST :", min([], default=0))  # set default to 0
    print("MIN OF LITERALS :", min(numbers, key=int)) # convert all items into integer before comparing. 

if __name__ == '__main__':
    find_min()

Output

min() - Output

#6) max()

The Python max() function returns the highest item in a sequence.

Syntax:

max(iterable[,key, default])

Where:

  • iterable here will be a list of items.
  • key here specifies a function of one argument that is used to extract a comparison key from each list element.
  • default here specifies a value that will be returned if the iterable is empty.

Example 8: Find the largest number in the list [4,3,9,10,33,90].

>>> numbers = [4,3,9,10,33,90]
>>> max(numbers)
90

#7) sorted()

The Python sorted() method returns a new sorted list of items from an iterable.

Syntax:

sorted(iterable[,key,reverse])

Where:

  • iterable here will be a list of items.
  • key here specifies a function of one argument that is used to extract a comparison key from each list element.
  • reverse is a bool that specifies if the sorting should be done in ascending(False) or descending(True) order. It defaults to False.

Example 9: Sort the list [4,3,10,6,21,9,23] in descending order.

>>> numbers = [4,3,10,6,21,9,23]
>>> sorted(numbers, reverse=True)
[23, 21, 10, 9, 6, 4, 3]

Example 10: Sort the list in descending order only using the key keyword.

Here, we will use the lambda expression to return the negative value of each item for comparison. So, instead of sorting the positive numbers, sorted() will now sort negative values, hence the result will be in descending order.

>>> sorted(numbers, key=lambda x: -x)
[23, 21, 10, 9, 6, 4, 3]

Note: The Python sorted() function is a bit similar to the Python list method sort(). The main difference is that the list method sorts in-place and returns None.

#8) reversed()

The Python reversed() function returns a reverse iterator in which we can request the next value or iterate through until we hit the end.

Syntax:

reversed(iterator)

Example 11: Find the reverse order of the list.

>>> numbers = [4,3,10,6,21,-9,23]
>>> list(reversed(numbers))
[23, -9, 21, 6, 10, 3, 4]

Note:

We should note the following

  • As reversed() returns a generator expression, we can use list() to create the list of items.
  • The Python reversed() function is similar to the list method reverse(). However, the latter reverses the list in-place.
  • Using slicing(a[::-1]), we can reverse a list similar to the reversed() function.

#9) enumerate()

The Python enumerate() function returns an enumerate object in which we can request the next value or iterate through until we hit the end.

Syntax:

enumerate(sequence, start=0)

Each next item of the returned object is a tuple (count, item) where the count starts from 0 as default, and the item is gotten from iterating through the iterator.

Example 12: Enumerate the list of names [“eyong”,”kevin”,”enow”,”ayamba”,”derick”] with the count starting from 3 and returns a list of tuples such as (count, item).

>>> names = ["eyong","kevin","enow","ayamba","derick"]
>>> list(enumerate(names, 3))
[(3, 'eyong'), (4, 'kevin'), (5, 'enow'), (6, 'ayamba'), (7, 'derick')]

The Python enumerate() function can be implemented using a traditional for loop.

def enumerate(seqs, start=0):
    count = start   # initialize a count
    # loop through the sequence
    for seq in seqs:
        yield count, seq  # return a generator object
        count +=1 # increment our count
    
if __name__ == '__main__':
    names = ["eyong","kevin","enow","ayamba","derick"]
    start = 3
    print("ENUMERATE: ", list(enumerate(names, start)))

Output

enumerate - output

Note: In the enumerate() function above, we used the Python keyword yield that returns a generator object which needs to be iterated to give values.

#10) zip()

The Python zip() function returns an iterator that contains an aggregate of each item of the iterables.

Syntax:

zip(*iterables)

Where the * indicates that the zip() function can take any number of iterables.

Example 13: Add the i-th item of each list.

def add_items(l1, l2):
    result = [] # define an empty list to hold the result

    # aggregate each item of the lists
    # for each iteration, item1 and item2 comes from l1 and l2 respectively
    for item1, item2 in zip(l1, l2):
        result.append(item1 + item2) # add and append.

    return result

if __name__ == '__main__':
    list_1 = [4,6,1,9]
    list_2 = [9,0,2,7]

    print("RESULT: ", add_items(list_1, list_2))

Output

Zip - Output

Note: It is important to note that this resulting iterator stops when the shortest iterable argument is exhausted.

>>> l1 = [3,4,7] # list with size 3
>>> l2 = [0,1]   # list with size 2(shortest iterable)
>>> list(zip(l1,l2))
[(3, 0), (4, 1)]

The result above didn’t include 7 from l1. This is because l2 is 1 item shorter than l2.

#11) map()

The Python map() function maps a function to each item of iterables and returns an iterator.

Syntax:

map(function, iterable,...]

This function is mostly used when we want to apply a function on each item of iterables but we don’t want to use the traditional for loop.

Example 14: Add 2 to each item of the list

>>> l1 = [6,4,8,9,2,3,6]
>>> list(map(lambda x: x+2, l1))
[8, 6, 10, 11, 4, 5, 8]

In the example above, we used lambda expressions to add 2 to each item and we used the Python list() function to create a list from the iterator returned by the map() function.

We could achieve the same result in Example 14 with traditional for loop as shown below:

 def map_add_2(l):
    result = [] # create empty list to hold result
    # iterate over the list
    for item in l:
        result.append(item+2) # add 2 and append
    return result
    
if __name__ == '__main__':
    l1 = [6,4,8,9,2,3,6]
    print("MAP: ", map_add_2(l1))

Output

map() - example

Note: The map() function can take any number of iterables given that the function argument has an equivalent number of arguments to handle each item from each iterable. Like zip(), the iterator stops when the shortest iterable argument is exhausted.

>>> l1 = [6,4,8,9,2,3,6]  # list of size 7
>>> l2 = [0,1,5,7,3]      # list of size 5(shortest iterable)
>>> list(map(lambda x,y: (x+2,y+2), l1,l2)) #lambda accepts two args
[(8, 2), (6, 3), (10, 7), (11, 9), (4, 5)]

We could achieve the same result above with the Python zip() function in traditional for loop as below:

def map_zip(l1,l2):
    result = [] # create empty list to hold result
    # iterate over the lists
    for item1, item2 in zip(l1, l2):
        result.append((item1+2, item2+2)) # add 2 and append
    return result
    
if __name__ == '__main__':
    l1 = [6,4,8,9,2,3,6]
    l2 = [0,1,5,7,3]
    print("MAP ZIP: ", map_zip(l1,l2))

Output

map_zip - output

#12) filter()

The Python filter() method constructs an iterator from the items of iterables that satisfy a certain condition

Syntax:

filter(function, iterable)

The function argument sets the condition that needs to be satisfied by the items of the iterable. Items that do not satisfy the condition are removed.

Example 15: Filter out the names with length smaller than 4 from the list [“john”,”petter”,”job”,”paul”,”mat”].

>>> names = ["john","petter","job","paul","mat"]
>>> list(filter(lambda name: len(name) >=4, names))
['john', 'petter', 'paul']

Note: If the function argument is None, then all items that evaluate to false like False, ‘ ‘, 0, {}, None, etc will be removed.

>>> list(filter(None, [0,'',False, None,{},[]]))
[]

Note: We could achieve the result in the example 15 above with list comprehensions.

>>> names = ["john","petter","job","paul","mat"]
>>> [name for name in names if len(name) >=4]
['john', 'petter', 'paul']

#13) iter()

The Python iter() function converts an iterable into an iterator in which we can request the next value or iterate through until we hit the end.

Syntax:

iter(object[,sentinel])

Where:

  • object can be represented differently based on the presence of sentinel. It should be an iterable or sequence if a sentinel is not provided or a callable object otherwise.
  • sentinel specifies a value that will determine the end of the sequence.

Example 16: Convert the list [‘a’,’b’,’c’,’d’,’e’] into an iterator and use next() to print each value.

>>> l1 = ['a','b','c','d','e'] # create our list of letters 
>>> iter_list = iter(l1) # convert list to iterator
>>> next(iter_list)    # access the next item
'a'
>>> next(iter_list)    # access the next item
'b'
>>> next(iter_list)    # access the next item
'c'
>>> next(iter_list)    # access the next item
'd'
>>> next(iter_list)    # access the next item
'e'
>>> next(iter_list)    # access the next item
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

In the example above, we see that after accessing the last item of our iterator, the StopIteration exception is raised if we try to call next() again.

Example 17: Define a custom object of prime numbers and use the sentinel parameter to print the prime numbers till 31 inclusive.

Note: If a user-defined object that is used in iter() doesn’t implement the __inter__(), __next__() or the __getitem__() method, then a TypeError exception will be raised.

class Primes:
    def __init__(self):
        # prime numbers start from 2.
        self.start_prime = 2

    def __iter__(self):
        """return the class object"""
        return self

    def __next__(self):
        """ generate the next prime"""
        while True:
            for i in range(2, self.start_prime):
                if(self.start_prime % i) ==0:
                    self.start_prime += 1
                    break
            else:
                self.start_prime += 1
                return self.start_prime - 1

    # each time this class is called as a function, our __next__ function is called       
    __call__ = __next__

if __name__ == "__main__":
    # Since we want prime numbers till 31, we define our sentinel to be 37 which is the next prime after 31. 
    prime_iter = iter(Primes(), 37)
    # print items of the iterator
    for prime in prime_iter:
        print(prime)

Output

iter() - example

Other Python List Built-in Functions

#14) all()

The Python all() function returns True if all the elements of an iterable are true, or if the iterable is empty.

Syntax

all(iterable)

Note:

  • In Python, False; empty list([]), strings(”), dict({}); zero(0), None, etc are all false.
  • Since the Python all() function takes in an iterable argument, if an empty list is passed as an argument, then it will return True. However, if a list of an empty list is passed, then it will return False.

Example 18: Check if all items of a list are true.

>>> l = [3,'hello',0, -2]  # note that a negative number is not false
>>> all(l)
False

In the example above, the result is False as element 0 in the list is not true.

#15) any()

The Python any() function returns True if at least one item of the iterable is true. Unlike all(), it will return False if the iterable is empty.

Syntax:

any(iterable)

Example 19: Check if at least one item of the list [‘hi’,[4,9],-4,True] is true.

>>> l1 = ['hi',[4,9],-4,True] # all is true
>>> any(l1)
True
>>> l2 = ['',[],{},False,0,None] # all is false
>>> any(l2)
False

Frequently Asked Questions

Q #1) What is a built-in function in Python?

Answer: In Python, built-in functions are predefined functions that are available for use without importing them. For example, len(), map(), zip(), range(), etc.

Q #2) How do I check for built-in functions in Python?

Answer: The Python built-in functions are available and well documented in the Python official documentation page here

Q #3) How can we sort a list in Python?

Answer: In Python, we can commonly sort a list in two ways. The first is using the list method sort() which will sort the list in-place. Or we use the Python built-in sorted() function which returns a new sorted list.

Q #4) How can you reverse a number in Python using the list method reverse()?

Answer:

We can do it as shown below:

  • First convert the number to a string, thereby making it iterable.
  • Then use list() to convert to a list.
  • Use the Python list method reverse() to reverse the list.
  • Use join() to join each element of the list.
  • Use int() to convert it back into a number.
>>> numb = 3528  # number to reverse
>>> str_numb = str(numb) # convert to a string, making it iterable.
>>> str_numb
'3528'
>>> list_numb = list(str_numb) # create a list from the string. 
>>> list_numb
['3', '5', '2', '8']
>>> list_numb.reverse() # reverse the list in-place
>>> list_numb
['8', '2', '5', '3']
>>> reversed_numb = ''.join(list_numb)   # join the list
>>> int(reversed_numb)  # convert back to integer.
8253

Q #5) How do you reverse a list without reverse in Python?

Answer: The common way to reverse a list without using the Python reverse() list method or built-in function reversed() is to use slicing.

>>> l = [4,5,3,0] # list to be reversed
>>> l[::-1]  # use slicing
[0, 3, 5, 4]

Q #6) Can you zip three lists in Python?

Answer: The Python zip() function can take in as many iterables as your computer can support. We just have to make sure that when used in a for-loop, we should provide enough variables to unpack, otherwise a ValueError exception will be raised.

>>> for x,y,z in zip([4,3],('a','b'),'tb'):
...     print(x,y,z)
... 
4 a t
3 b b

Conclusion

In this tutorial, we saw some of the commonly used Python built-in functions like min(), range(), sorted(), etc.

We also discussed some uncommonly used list built-in functions like any() and all(). For each function, we demonstrated its usage and saw how it applies on lists with examples.

=> Visit Here To Learn Python From Scratch