How to Create and Use Lists (Arrays) in Python

A list is a data type used in Python to store lists of items. Lists work in a similar way to array functions you would find in other programming languages like PHP or Java. They are useful for storing items so they can be sorted, removed, added, counted and accessed efficiently.

 

In this tutorial, we will learn how to use lists in Python with examples of how they can be used to work with data.

 

How to Create a List

To create a list type [] (opening and closing square brackets). In the example below, we are creating a list that is assigned to the variable numbers so that it can be used later in the program.

 

numbers = []

 

To create an array containing elements we can add the elements inside the square brackets separated by , (commas).

 

numbers = [1,2,3]

 

All the Python List Functions

For reference here are all the built-in Python functions that you can use to work with lists.

 

  • index()
  • append()
  • extend()
  • insert()
  • remove()
  • count()
  • pop()
  • reverse()
  • sort()
  • copy()
  • clear()

 

How to Add to a List in Python

New elements can be added to a list VIA the append function. Pass the value to add inside the () (parenthesis) of the append function and it will be added to the end of the list.

 

numbers = [1,2,3]

numbers.append(4)

print(numbers)
[1, 2, 3, 4]

 

Unlike some other languages, you can append mixed data types to an array such as numbers and strings.

 

numbers = [1,2,3]

numbers.append("hi")

print(numbers)
[1, 2, 3, 'hi']

 

Get a List Element Value

Values in a list can be accessed by passing in [] (square brackets) containing the index of the element to get on the list variable. Indexes in lists start at 0 so the highest index will be one less than the count of the elements in the list.

 

numbers = [1,2,3]

first = numbers[0]

print(first)
1

 

Assign a New Value to a List Element

New values are set by getting the index of the element followed by = (equals) and then the value to set.

 

numbers = [1,2,3]

numbers[0] = 5

print(numbers)
[5, 2, 3]

 

Multi-dimensional Lists

It is possible to add a list into a list, making a multidimensional list. The example below uses the append function to add a new element containing a list.

 

numbers = [1, 2, 3]

numbers.append([2, 2])

print(numbers)
[1, 2, 3, [2, 2]]

 

To access an element inside of a multidimensional list, chain [] (square brackets) to the correct nesting level.

 

print(numbers[3][0])
2

 

Remove a List Element in Python

To remove the last element from the list use the pop function.

 

numbers = [1, 2, 3]

numbers.pop()

print(numbers)
[1, 2]

 

To remove a specific index, pass the index to remove inside of the () (parenthesis).

 

numbers.pop(0)
print(numbers)
[2, 3]

 

Slice List in Python

It is possible to slice a range of indexes from a list in Python. This is done by passing in the range  [ start : stop : step ] to the list variable and setting the value to [] (empty square brackets);

 

In the example below, we are removing indexes 0 to 1.

 

numbers = [1, 2, 3]
numbers[0:2] = []
print(numbers)
[3]

 

Python List index() Function

The index function is used to search for an element based on its value and return its index. It takes a required element parameter and two optional parameters for specifying on what index to start and end the search.

 

index( element_value, start_index, end_index )

 

Let's get the index of a in the following example:

 

letters = ['a', 'b', 'c']
print(letters.index('a'))
0

 

note -  index only returns the index of the first element match.

 

Python List extend() Function

To add a list of elements to the end of another list use the extend function. Anything iterable can be added using this method; a list, tuple, string .etc.

 

letters = ['a', 'b', 'c']
letters2 = ['d', 'e', 'f']

letters.extend(letters2)

print(letters)
['a', 'b', 'c', 'd', 'e', 'f']

 

Python List insert() Function

The insert list function can be used to add a new element to a list at a specific index. To use it pass in the index as the first argument and the value as the second.

 

letters = ['a', 'b', 'c']

letters.insert(1, 'd')

print(letters)
['a', 'd', 'b', 'c']

 

Python List remove() Function

The remove list function is used to search for an element by its value and remove it from the list. It only removes the first match. 

 

letters = ['a', 'b', 'c']

letters.remove('b')

print(letters)
['a', 'c']

 

If no matches are found a valueError is thrown:

 

letters.remove('d')
ValueError                                Traceback (most recent call last)
<ipython-input-10-a3222769419b> in <module>
      1 letters = ['a', 'b', 'c']
      2 
----> 3 letters.remove('d')
      4 
      5 print(letters)

ValueError: list.remove(x): x not in list

 

Python List count() Function

The count list function is used to get the total count of elements that have a specific value in a list. If no matches are found 0 will be returned.

 

letters = ['a', 'b', 'c', 'b']

print(letters.count('b'))
2

 

Python List reverse() Function

The reverse list function does exactly what it says in the tin. It reverses the order of a list. This function takes no arguments.

 

letters = ['a', 'b', 'c', 'd']

letters.reverse()

print(letters)
['d', 'c', 'b', 'a']

 

Python List sort() Function

The sort list function is used to sort a list in ascending or descending order. To sort the list in descending order use sort() with no arguments:

 

letters = ['d', 'c', 'b', 'a']

letters.sort()

print(letters)
['a', 'b', 'c', 'd']

 

To sort a list in descending order pass in reverse=True as an argument:

 

letters = ['a', 'b', 'c', 'd']

letters.sort(reverse=True)

print(letters)
['d', 'c', 'b', 'a']

 

An additional key= argument can be passed into sort to sort the list by a custom value. In the example below we are sorting a list by the length of the element and setting the order to descending:

 

letters = ['aaa','aa', 'a', 'aaaa']

letters.sort(reverse=True, key=len)

print(letters)
['aaaa', 'aaa', 'aa', 'a']

 

Python List copy() Function

The copy function makes a copy of a list. Using copy will mean the new list will not reference the old one, unlike simply assigning the list to a new variable.

 

letters = ['a', 'b', 'c']
new_letters = letters.copy()

letters.remove('a')
new_letters.append('d')

print(letters)
print(new_letters)
['b', 'c']
['a', 'b', 'c', 'd']

 

 

Python List clear() Function

The clear function is used to remove all elements from a list. It leaves an empty list and does not take any arguments.

 

letters = ['a', 'b', 'c']
letters.clear()
print(letters)
[]

 

Conclusion

You now know how to use lists in Python and how to work with the data in various ways, including with Pythons native list functions. There are quite a few list functions to remember, but they are logically named so they will come naturally to you once you have been working with them for a while.

list array sort element