Lists

A list in Python is a data type used to store a collection of objects.

Lists are always ordered and can contain different types of objects, such as strings, integers, booleans, etc. Lists are a mutable data type and therefore a good choice for dynamic data (adding and subtracting to lists).

Creating a List

There are multiple ways to define a list in Python. We can either assign a variable to a pair of square brackets ([]) with or without values, or we can assign a variable to the list() keyword and afterwords pass in its list items.

Defining empty lists:

Loading...

Creating lists with values in them:

Loading...

Using a Built-in List Method

Loading...

The output would be:

Loading...

Lists

.append()
Adds an item to end of the list.
.clear()
Removes all items from the list.
.copy()
Returns a shallow copy of a list.
.count()
Searches a list for a particular item and returns the number of matching entries found.
.extend()
Adds list elements to end of the list.
.index()
Finds the first occurence of a particular value within the list.
.insert()
Adds an item at a specified index in the list.
.pop()
Removes an item from a list while also returning it.
.remove()
Remove an item from a list by passing in the value of the item to be removed as an argument.
.reverse()
Reverse the elements in the list.
.sort()
Sort the contents of the list it is called on.
Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn Python on Codecademy