Python Lists
Start your free 7-days trial now!
A list is a collection of elements in a particular order. In Python, a list is represented by square brackets []
.
['apple', 'orange', 'pear']
Note that when you print a list, the square brackets are also returned.
Examples
Accessing elements in a list
We can access a particular element in a list by its index position:
fruits = ["apple", "orange","pear"]
orange
Note index positions start at 0 not 1. Therefore by specifying fruits[1]
we returned the second item in list fruits
.
We can return the last item in a list by specifying index of -1
:
fruits = ["apple", "orange","pear"]
pear
This method is useful when you do not know the length of the list you are working with.
Modifying elements in a list
We can also use index notation to modify elements in a list:
['apple', 'raspberry', 'pear']
The second element in the list "orange"
has been replaced with new value "raspberry"
.
Slicing a list
To create a slice of the second and third items in a list:
fruits = ["apple", "orange","pear"]fruits[1:3]
['orange', 'pear']
fruits[1:3]
gets elements of fruits
starting from index 1 up until but not including index 3.