List
List is one of the compound data types in Python. Lists can group together elements.
A list is written as a comma-separated ,
elements (values or items) between square brackets []
. Lists might contain elements of different types, but usually the elements all have the same type.
Python lists are:
Lists can be empty
Lists can have any elements
Lists are ordered
List elements can be accessed by index
Lists can be nested to any arbitrary depth
Lists are mutable, i.e. they can be modified after they are created
Lists can be empty
An empty list can be created by assigning empty square brackets to an identifier.
Lists can have any elements
Lists can contain a single datatype or a mixture of datatypes.
Lists are ordered
The order of elements in a list is important. Two lists are not the same if the elements within a list are same but in a different order.
These two lists have the same elements but in different order
You can use is keyword too.
List elements can be accessed by index
You can use the index operator of square brackets[]
to access an element in a list. In Python, index starts from 0.
Index number should be an integer, otherwise it raises TypeError
. Python will raise an IndexError
if the index element is outside of the length of the list minus one.
Positive Indexing
The indices for the elements are as follow:
You can access each element by writing the name of the list
followed by square brackets []
and index number
of the element.
Negative indexing
Python allows negative indexing for elements in a list. Negative index counts from the end of the list. -1 is the index of last element, -2 is the index of second from last element, so on.
You can access elements in a list using negative index.
List slicing in Python
Slicing of a list needs two indices: start index
and end index
separated by a colon :
All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list.
You create a new list using slice operations. Square brackets []
with colon :
will select all elements in the list and assign it to a new list
Let's compare my_list
with new_list
While comparing new_list
with my_list
with ==
, Python returns True
but comparison with Python keyword is
returns False
. ==
compares the orders of elements in themy_list
and new_list
but Pythonis
keyword is referencing memory locations of the my_list
and new_list
which are different and returns False.
Slicing to select/filter elements
Let's say you want to get the 2nd to 7th elements. Our start index is 1 and end index is 7 (End index returns the index before index 7, so in this case until index 6).
Lists usually start counting from left to right. Empty start index location means select/filter elements from the start.
Empty end index location means select/filter the elements from start index to the last element in the list.
You can use a mixture of index and negative index together. For example; let's select 2nd element from start until 3rd element from the end. 2nd element has index of 1 (Python starts zero index) and 3rd element from end has index of -2, end index returns the (index - 1), meaning index is bigger by one number.
Stride
You can specify a stride—either positive or negative. Stride is added to the square bracket as a second colon :
, the stride form will be [start_index : end_index : step]
. Step control defines how many elements to skip before selecting next element.
List reverse
Python lets you to easily reverse lists
Lists can be nested
A list can contain sublists, which in turn can contain sublists themselves.
Each element in list or its sublists can be accessed with element index.
Each sublist adds another square bracket to access its elements. my_list[3][1]
returns index 3 of main list and an element at index 1 of the sublist
Simply append another square bracket. All operation of slicing can also be performed on the second square bracket, etc.
Lists are mutable
Elements with a list can be deleted, shifted, updated or modified after the list has been created. You can change each element of a list or append new elements to a list.
You can use assignment operator (=
) to change an item or a range of items.
Updating a single element
A single value in a list can be replaced by indexing and assignment operator.
Updating multiple elements
Multiple elements can be update by specifying the elements index
Deleting a single element
An element or elements can be deleted using del
keyword.
First example deletes element [7]
, second example deletes three elements [5, 5, 7]
.
Prepending or appending elements to a list
An element or elements can be added to the start or end of a list using the +
operator. This is also called concatenation.
If you want to add a single element, we have to wrap it in square brackets []
. Otherwise, Python raises a TypeError
.
The =
assignment operator can be used to save the prepending or appending elements.
The +=
augmented assignment operator works only when we append elements to a list
The *
operator repeats a list for a given number of times.
List methods
list methods modify the target list in place. They do not return a new list. We do not need to use assignment operators such as =
.
append()
append()
You can use append()
to added an element to the end of a list.
A list can be added to another list, but it will append the list as a sublist rather than extending the elements within the main list (it is added as a single object).
extend()
extend()
Similar to append()
, extend()
also adds element/s to the end of a list and only modifies the original list. the argument between ()
should be an iterable, i.e., adding an element at a time.
You can see the difference between append()
and extend()
methods when adding a list to a list. append()
adds as a sublist but extend()
adds an element at a time
insert()
insert()
You can insert one element at a desired location by using the method insert()
. insert() takes two arguments:
The index location to add the element and
the element (string, float, integer etc).
The newly inserted element will push the elements from the index insert location to the right.
pop()
pop()
The pop()
removes and returns the last element when no index is provided. You can use pop()
with an index to remove element at the given index. pop()
is helpful because it may insert or remove an element from only one end, as a result, lists can be implemented as stacks (last-in, first-out).
remove()
remove()
You can use remove()
method to remove a given element. You have to provide the element (not its index).
remove()
removes only the FIRST occurrence of the element.
You can check the Jupyter Notebook in GitHub or Colab.
Last updated
Was this helpful?