Lists
A list is a collection of ordered items.
Items in the list can be of any type: strings, numbers, dictionaries, lists, objects, ...
Use square brackets ([]) to create a list.
Use commas to separate items in the list.
Accessing items in a list:
To access an item in a list, you use square brackets ([]) with the index of that item in the list.
The index of the first item in the list is 0, and the next one is 1, ...
You can access items in a list from the last index using negative numbers.
The index of the last item is -1, and the one before the last one is -2, ...
If the list is empty, using any index to access an item in the list will return an error.
Using an index that's higher than the list size will return an error.
Appending items to the end of a list:
Inserting items into a list:
Modifying items in a list (you can modify an item from any position in the list):
Removing an item using the del statement (you can remove an item from any position in the list):
Removing the last item in a list (the item removed can be assigned or printed if needed):
Removing an item from a specific position in a list (the item removed can be assigned or printed if needed):
Removing an item by its value from a list (the function remove deletes only the first occurrence of the value):
Sorting permanently a list: sort()
Sorting temporarily a list: sorted()
Reversing items of a list (no sorting):
Finding the length of a list:
Looping through a list:
Note that the variable "y" will be accessible after the loop finishes.
Note that the indentation is very important to limit the block of the instructions that are part of the loop.
Using the range() function:
The range function has two parameters.
The value of the first parameter is inclusive in the range.
The value of the second parameter is exclusive from the range.
Making a list of numbers using range() function:
Returning the min, max, and sum of items of a list:
List comprehensions (provide a concise way to create lists):
Slicing a list:
You can specify the index of the first item (inclusive) and the last item (exclusive):
You can skip the index of the first item (defaults to 0)
You can skip the index of the last item (defaults to the length of the list):
You can skip the index of the first and last item (useful to copy a list): index of the first item default to 0 and the last defaults to the length of the list
To get the slice of the last items, you can use a negative index:
You can decide how many items to skip between items in the specified range by setting a third index in the brackets:
Looping through a slice:
Copying a list (a new list will be created):
Note that this is different from assigning the variable to another one which just creates another reference to the same list:
The enumerate() function:
The enumerate() function returns a key-value pair for each item in a list.
the key is the index of the item in the list and the value is the item.