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:
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']
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()
- Removes 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()
- Sorts the contents of the list it is called on.