Python Lists
A list is a sequence of values. You could visualize a list as a container that holds a number of items, in a given order.
To create a list in Python, simply add any number of comma separated values between square brackets. Like this:
In Python, a list can contain items of varying data types. For example, here's a list that contains a string, an integer, and another list.
When we print both of those lists we get this:
['Earth', 'Mars', 'Saturn', 'Jupiter'] ['Hey', 123, ['Dog', 'Cat', 'Bird']]
Return the Number of items in a List
You can use the len()
function to return the number of items in a list. Adding the len()
function to the print()
function will print that number out.
Accessing a List Item
You can pick out a single list item by referring to its index. Remember, Python uses zero-based indexing, so start the count at 0
when doing this.
So to find out what the second item in the planet
list is, do this:
You can also select a range of items by specifying two indexes separated by a colon. Like this:
['Mars', 'Saturn']
Notice that it doesn't actually include the upper index specified? I specified 1:3
but it only returned two values. This is because Python only returns the list items up to, but not including, the last index specified.
Negative Indexing
You can use a negative index to start counting from the end of the list. In this case, the count starts at -1
(not zero). So an index of -1
is the last item, -2
is the second last item, and so on.
Example:
Saturn
Update a List Item
You can change a list item like this:
So it's like setting a variable, but appending the variable name with the list item's index inside square brackets.
Here's a demonstration:
['Earth', 'Mars', 'Saturn', 'Jupiter'] ['Earth', 'Mercury', 'Saturn', 'Jupiter']
Append a List Item
You can add items to a list by using the append()
function. Here's an example:
Here's a demonstration:
['Earth', 'Mars', 'Saturn', 'Jupiter'] ['Earth', 'Mars', 'Saturn', 'Jupiter', 'Mercury']
Delete a List Item
Use the del
keyword to delete a list item at a particular index. Like this:
Here's a demonstration:
['Earth', 'Mars', 'Saturn', 'Jupiter'] ['Earth', 'Mars', 'Jupiter']