Python Basics
Variables & Comments Math Operators Sequence Data Types Strings Lists & Tuples Logical Operators Conditional Statements Loops Functions
Data Wrangling
Pandas Introduction Importing Data Select, Drop & Rename Joining Data Cleaning Data Add Columns Dates
Coming Soon
Machine Learning
Coming Soon
Other Tutorials & Content
Python Data Science Reference Blog

Python Lists & Tuples

Creating Lists in Python

Python Lists are created by assigning elements between brackets with a comma separating each list element. Lists can be as large as required and can contain a mixture of data types; elements can even be another sequence type.

string_list = ['one', 'two', 'three']
int_list = [1, 2, 3, 4]
mixed_list = [1, 'two', 3]
> ['one', 'two', 'three']

Python List Index

Elements in a list can be referenced by calling the list name followed by the index of the position between brackets or by referencing an index range just like with Strings.

> one
> [1, 2]

Using List Elements

We can treat each List element as a separate variable that then can be used in other tasks just like regular variables can be.

new_int = int_list[0] + int_list[1]
> 3

Python List Length

Just like all sequence data types, we can use the Pyton LEN function to find out how elements are in a list.

> 4

Python Append to List

Python Lists come with a couple of functions that allow us to quickly add and remove elements. To add an element to the end of a list we simply use the Append function and the new element we want to add.

> ['one', 'two', 'three', 'four']

Python Remove from List

Similarly, to remove an element we can use the Remove function.

> ['one', 'two', 'three']

In the case of the Remove function, it’s worth remembering that removing an element will cause all values that were stored in later indexes to be moved up to an earlier position in the list.

Reassigning Python List Elements

Finally, we can reassign any part of a list with another value, as we can with regular variables.

string_list[0] = 1
> [1, 'two', 'three']

Python Tuples

Tuples are very similar to Python Lists and are assigned by declaring the Tuple elements within open brackets, separated by a comma.

new_tuple = ['Mon', 'Tues', 'Wed']
> ('Mon', 'Tues', 'Wed')
> Mon

Tuple TypeError

Python Tuples can be comprised of different data types, can be referenced using index numbers or index ranges and we can use the Python LEN function to determine the length of a Tuple. However unlike Python Lists, Python Tuples are constant, meaning they cannot be changed. If we attempt to reassign any element within a Tuple we will get a Type Error.

new_tuple[2] = 'Thur'

> TypeError: 'tuple' object does not support item assignment