List

A list, also known as an array, is a versatile data structure that allows you to store multiple objects at a time. Lists are used in almost every interview question whenever we need to work with a collection of objects.

Creating lists

The most common way to create a list is using square brackets. Another way is by using the list() function, however it's best to stick to one approach for interview practice.

You can also initialize lists with predefined values.

Note

Unlike some languages, it is allowed to put objects of different classes into the same list in Python.

Adding to a list

O(n) or O(1)

Here are two common methods to add elements to a list:

  • append() adds the element to the end of the list
  • insert() takes in a second argument that specifies what position to add the element at

Note

insert() is an O(n) complexity operation whereas append() is an O(1) operation, so use insert() sparingly. If you need to only add to the front, consider using a queue (covered in a later chapter!).

Removing an item from a list

O(n) or O(1)

There are two ways to remove an item from a list:

  • pop() removes an element at the last index
  • remove() removes an element by object value

Note

Both remove() and pop(x) are O(n) operations.pop(x) is an O(1) operation if no index is specified.

Getting values from lists

O(1)

You can use the subscript operator to access a value in a list.