Python Lists

Posted 

8 min read

Python includes a number of sequential data types that allow you to store collections of data in an organized and efficient way. The basic sequence types are lists, tuples, and range objects.

This article goes through the Python lists. We’ll show you how to create a list, slice and sort a list, add or remove elements from a list, and so on.

Lists are mutable sequences, which means that they can be changed after creation. Lists are one of the most commonly used data types in Python and are generally used to store collections of items of the same type.

Creating a List

Lists are typically created by placing the items inside a pair of square brackets [], separated by commas. They can have any number of items, which may be of different types. Here is an example:

L = ['orange', 'white', 'green']

Square brackets with no elements in between them denote an empty list:

L = []

Although Python lists are generally homogeneous, you can have items with mixed data types:

L = [1, 'white', 6.5]

You can also declare nested lists where one ore more items are also lists:

L = [1, 2, ['red', 'blue']]

Multiple elements can have the same value:

L = [1, 2, 3, 2, 2, 1]

Lists may also be constructed using a list comprehension, the list() constructor, and other built-in functions such as sorted().

Accessing the List Elements

A list item can be referenced by its index. Indexes are integers and start from 0 to n-1 where n is the number of items:

L = ["a", "b", "c", "d"]
      0    1    2    3

In Python indexes are enclosed with square brackets:

L[index]

For example, to access the second element of the list you would use:

colors = ['orange', 'white', 'green']colors[1]
'white'

If you reference an index that doesn’t exist, an IndexError exception is raised:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

To access items in a nested list use multiple indexes:

L = [1, 2, ["red", "blue"]]L[2][1]
'blue'

Python also allows you to access the list items using negative indexes. The last item is referred to as -1, the second last item as -2 and so on:

L = ["a", "b", "c", "d"]
     -4   -3   -2   -1

For example, to access the second element from the end, you would use:

colors = ['orange', 'white', 'green']colors[-2]
'white'

Slicing a List

In Python, you can slice a list using the following form:

L[start:stop:step]
  • The first argument specifies the index at which the extraction begins. When a negative index is used, it indicates an offset from the end of the list. If this argument is omitted, slicing begins from index 0.
  • The second argument specifies the index before which to end extraction; the result doesn’t include the “stop” element. When a negative index is used, it indicates an offset from the end of the list. If this argument is omitted or greater than the length of the list, slicing goes to the end of the list.
  • The third argument is optional and specifies the step of the slicing. When the “step” argument is not used, it defaults to 1. When a negative value is used, the slice takes elements in reverse order.

The result of slicing a list is a new list containing the extracted elements, and the original list is not modified.

All the following is legal Python syntax:

L[:] # copy whole list
L[start:] # slice the list starting from the element with index "start" to the end of the list.
L[:stop] # slice the list starting from the begging up to but not including the element with index "stop".
L[start:stop] #  slice the list starting from the element with index "start" up to but not including the element with index "stop".
stop"
L[::step] #  slice the list with a stride of "step"

Below is a basic example of how to slice a list starting from the element with index 1 up to but not including the element with index 4:

fruits = ['Apple', 'Peach', 'Lemon', 'Strawberry', 'Grape']fruits[1:4]
['Peach', 'Lemon', 'Strawberry']

Updating Element Value

To change the value of a specific item in a list, refer to its index number:

L[index] = value

Here is an example showing how to update the value of the list’s last element:

colors = ['orange', 'white', 'green']colors[-1] = "blue"print(colors)
['orange', 'white', 'blue']

If the element with the given index exists, the value is updated. Otherwise an IndexError exception is raised:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

You can also update a slice of a list with new values:

colors = ['orange', 'white', 'green']colors[1:3] = ['red']print(colors)
['orange', 'red']

The replacement chunk can have smaller, bigger or the same number of items as the list. This allows you to expand or shrink the list.

Adding Elements to a List

The list data type has two methods that allow you to add elements to a list , append() and insert().

The append() method adds an item to the end of the list. The syntax of append() method is as follows:

L.append(element)

“element” is the item to be appended in the list. It can be any data type including a list. Here is an example:

colors = ['orange', 'white', 'green']colors.append('red')print(colors)
['orange', 'white', 'green', 'red']

The insert() method ads an item at a specific position in a list, and has the following syntax:

L.insert(index, element)

“index” is the position where you want to insert the element and “element” is the item to be appended in the list. The following example shows how to add an element to a list at the first position:

colors = ['orange', 'white', 'green']colors.insert(0, 'red')print(colors)
['red', 'orange', 'white', 'green']

The extend() method allows you to extend a list with multiple elements. It takes a single argument and has the following syntax:

L.extend(list)

The elements of “list” are appended to the end of “L”. Here is an example:

colors = ['orange', 'white', 'green']colors.extend(['blue', 'black'])print(colors)
['orange', 'white', 'green', 'blue', 'black']

Removing Elements from a List

The remove() method takes one argument and removes the first element with value matching the argument from the list:

L.remove(element)
colors = ['orange', 'white', 'orange', 'green']colors.remove('orange')print(colors)
['white', 'orange', 'green']

If the element with the given value doesn’t exists, an ValueError exception is raised:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

The pop() method takes one argument and removes the element with index matching the argument from the list:

L.pop(element)

The argument is optional amd defaults to “-1”, which is the last item of the list. The return value of the method is the removed item. Here is an example:

colors = ['orange', 'white', 'green']colors.pop(1)print(colors)
'white'
['orange', 'green']

The del keyword in combination with the slice notation allows you to remove more than one items. For example to remove the first two items from a list you would use the following:

colors = ['orange', 'white', 'orange', 'green']del colors[0:2]print(colors)
['orange', 'green']

To remove all items use the clear() method, which clears the list and doesn’t accept any arguments:

colors = ['orange', 'white', 'green']colors.clear()print(colors)
[]

Find the Length of a List

The built-in len() function returns the total number of items of an object.

To find a length of a list, pass it as an argument to the len() function:

len(L)

Here is an example:

colors = ['orange', 'white', 'green']num = len(colors)print(num)
3

Iterating Through a List

To iterate through all items in a list use the for loop:

colors = ['orange', 'white', 'green']for color in colors:    print(color)
orange
white
green

If you need indexes, you have several methods at your disposal. The most common ways are to combine the range() and len() functions or to use the built-in enumerate() function.

The example below shows how to retrieve the index and the value of each item in the list:

colors = ['orange', 'white', 'green']for i in range(len(colors)):  print("Index {} : Value {}".format(i, colors[i]))
Index 0 : Value orange
Index 1 : Value white
Index 2 : Value green

Instead of using the range(len(...)) pattern you can use the enumerate() function to loop over a list in a more Pythonic way:

colors = ['orange', 'white', 'green']for index, value in enumerate(colors):   print("Index {} : Value {}".format(index, value))
Index 0 : Value orange
Index 1 : Value white
Index 2 : Value green

Check if an Element Exists

To check whether an item exist in a list, you can use the in and not in operators:

colors = ['orange', 'white', 'green']print('orange' in colors)

The output will be either True or False:

True

Here is another example using the if statement :

colors = ['orange', 'white', 'green']if 'blue' not in colors:    print('no')else:    print('yes')

The output will be either True or False:

no

Python List Methods

The list objects accepts the following methods:

  • append(x) - Appends an item at the end of the list.
  • clear() - Removes all items from the list.
  • copy() - Returns a shallow copy of the list.
  • count(x) - Returns the number of times ‘x’ appears in the list.
  • extend(iterable) - Appends the ‘iterable’ to the end of the list.
  • index(x) - Returns the position of the first occurrence of an element with value of ‘x’.
  • insert(i, x) - Adds an item at a given position.
  • pop(i) - Removes an item from a given position.
  • remove() - Removes the item with a given value.
  • reverse() - Reverses the elements of the list .
  • sort() - Sorts the items of the list.

Conclusion

In this article, we discussed how to create and work with lists in Python.

The list data type includes a number of useful methods.

If you have any questions or feedback, feel free to leave a comment