To create an empty list, use empty brackets or the list() function:
empty_list_1 = []
empty_list_2 = list()
List mutability
Lists are mutable, which means that you can change their contents after they are created.
my_list = ['Macduff', 'Malcolm', 'Macbeth', 'Banquo']
my_list[1:3] = [1, 2, 3, 4]
print(my_list)
List operations
Lists can be combined using the addition operator (+):
num_list = [1, 2, 3]
char_list = ['a', 'b', 'c']
num_list + char_list
They can also be multiplied using the multiplication operator (*):
list_a = ['a', 'b', 'c']
list_a * 2
But they cannot be subtracted or divided.
You can check whether a value is contained in a list by using the in operator:
num_list = [2, 4, 6]
print(5 in num_list)
print(5 not in num_list)
List methods
Lists are a core Python class. As you’ve learned, classes package data together with tools to work with it. Methods are functions that belong to a class. Lists have a number of built-in methods that are very useful.
char_list = ['b', 'c', 'a']
num_list = [2, 3, 1]
char_list.sort()
num_list.sort(reverse=True)
print(char_list)
print(num_list)
Content
Lists can contain any data type, and in any combination. So, a single list can contain strings, integers, floats, tuples, dictionaries, and other lists.
Note: The following code block is not interactive
my_list = [1, 2, 1, 2, 'And through', ['and', 'through']]
Additional resources
- For more information about lists, refer to An Informal Introduction to Python: Lists.
- For more list methods, refer to Data Structures: More on Lists.