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:
list1 = list2 = list()
Creating lists with values in them:
list1 = ['one', 2, 'three']list2 = [True, False, False, True, False]list3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]list4 = ['one', 2, True]list5 = ['one', 'two', 'three']
Using a Built-in List Method
friends = ['Sue', 'Bob']print(type(friends))# Use a built-in method to add Anna to the list of friends.friends.append('Anna')print(friends)
The output would be:
<class 'list'>['Sue', 'Bob', 'Anna']
- Adds an item to end of the list.
- Removes all items from the list.
- Returns a shallow copy of a list.
- Searches a list for a particular item and returns the number of matching entries found.
- Adds list elements to end of the list.
- Finds the first occurence of a particular value within the list.
- Adds an item at a specified index in the list.
- Removes an item from a list while also returning it.
- Removes an item from a list by passing in the value of the item to be removed as an argument.
- Reverse the elements in the list.
- Sorts the contents of the list it is called on.
- Anonymous contributors
Learn Python on Codecademy
- Anonymous contributorsAnonymous contributors