Python List
Syntax
A Python list is a collection of items that are ordered and changeable. Lists are written with square brackets, and the items are separated by commas.
Here is an example of a list in Python:
my_list = [1, 2, 3, 4, 5]
You can also create a list of strings or a list of mixed data types:
my_list = ['a', 'b', 'c', 'd'] my_list = [1, 'a', True, 3.14]
You can access the items in a list by referring to their index number. The index numbers start at 0 for the first item, 1 for the second item, and so on.
first_item = my_list[0] second_item = my_list[1]
You can also use negative index numbers to access items from the end of the list. For example, -1 refers to the last item, -2 refers to the second last item, and so on.
last_item = my_list[-1] second_last_item = my_list[-2]
List characteristics
Here are some characteristics of Python lists:
Lists are ordered, meaning that the items are stored in a specific order, and that order is preserved. To demonstrate this, we can create a list and access the items using their index numbers:
my_list = ['a', 'b', 'c', 'd'] print(my_list[0]) # 'a' print(my_list[1]) # 'b' print(my_list[2]) # 'c' print(my_list[3]) # 'd'
Lists are changeable, meaning that you can add, remove, or modify the items in a list. To demonstrate this, we can use the append() method to add an item to the end of a list, the insert() method to add an item at a specific index, and the remove() method to remove an item from a list:
my_list = ['a', 'b', 'c', 'd'] # Add an item to the end of the list my_list.append('e') print(my_list) # ['a', 'b', 'c', 'd', 'e'] # Add an item at a specific index my_list.insert(1, 'f') print(my_list) # ['a', 'f', 'b', 'c', 'd', 'e'] # Remove an item from the list my_list.remove('b') print(my_list) # ['a', 'f', 'c', 'd', 'e']
You can also modify an item in a list by accessing the item using its index and assigning it a new value:
my_list = ['a', 'b', 'c', 'd'] my_list[1] = 'f' print(my_list) # ['a', 'f', 'c', 'd']
Lists can contain any data type, including integers, strings, and even other lists. To demonstrate this, we can create a list of mixed data types:
my_list = [1, 'a', True, 3.14, [1, 2, 3]] print(my_list[0]) # 1 print(my_list[1]) # 'a' print(my_list[2]) # True print(my_list[3]) # 3.14 print(my_list[4]) # [1, 2, 3]
List Use Cases
Storing a collection of items
One common use case for lists is to store a collection of items. For example, you might have a list of student names, a list of numbers, or a list of strings.
student_names = ['Alice', 'Bob', 'Charlie', 'David'] numbers = [1, 2, 3, 4, 5] words = ['apple', 'banana', 'cherry']
Iterating over a collection of items
Another common use case for lists is to iterate over the items in a list using a for loop. This is useful when you want to perform the same action on each item in the list.
student_names = ['Alice', 'Bob', 'Charlie', 'David'] for name in student_names: print(f'Hello, {name}!')
Hello, Alice! Hello, Bob! Hello, Charlie! Hello, David!
Sorting a collection of items
You can use the built-in sorted() function to sort a list of items. This is useful when you want to order a list of items in a specific way.
numbers = [5, 2, 4, 1, 3] sorted_numbers = sorted(numbers) print(sorted_numbers) # [1, 2, 3, 4, 5] # You can also reverse the order by passing the "reverse" parameter reverse_sorted_numbers = sorted(numbers, reverse=True) print(reverse_sorted_numbers) # [5, 4, 3, 2, 1]
Checking for membership
You can use the in operator to check if an item is in a list. This is useful when you want to check if a value is present in a list.
numbers = [1, 2, 3, 4, 5] if 3 in numbers: print('3 is in the list') else: print('3 is not in the list')
3 is in the list
Best Practices
Note that some of the following points include concepts which will be covered in later chapters.
Use the built-in len() function to get the length of a list. This is often more efficient than manually counting the number of elements in the list.
my_list = [1, 2, 3, 4, 5] # Good list_length = len(my_list) print(list_length) # 5 # Bad list_length = 0 for item in my_list: list_length += 1 print(list_length) # 5
Use the in operator to check if an element is in a list. This is often more efficient than manually searching for the element in the list.
my_list = ['a', 'b', 'c', 'd'] # Good if 'c' in my_list: print("'c' is in the list") # Bad for item in my_list: if item == 'c': print("'c' is in the list") break
Use the built-in sorted() function to sort a list. This is often more efficient than manually sorting the list.
my_list = [5, 3, 2, 1, 4] # Good sorted_list = sorted(my_list) print(sorted_list) # [1, 2, 3, 4, 5] # Bad for i in range(len(my_list)): for j in range(i+1, len(my_list)): if my_list[i] > my_list[j]: my_list[i], my_list[j] = my_list[j], my_list[i] print(my_list) # [1, 2, 3, 4, 5]
Use list comprehension to create a new list based on an existing list. This is often more concise and efficient than using a loop.
my_list = [1, 2, 3, 4, 5] # Good new_list = [item * 2 for item in my_list] print(new_list) # [2, 4, 6, 8, 10] # Bad new_list = [] for item in my_list: new_list.append(item * 2) print(new_list) # [2, 4, 6, 8, 10]
Use the enumerate() function to iterate over a list and get the index and value of each element. This is often more convenient than using a loop with the range() function.
my_list = ['a', 'b', 'c', 'd'] # Good for i, item in enumerate(my_list): print(f"Index {i}: {item}") # Bad for i in range(len(my_list)): print(f"Index {i}: {my_list[i]}")