Python: Lists
A list in Python is a collection of comma-separated items enclosed within a pair of square brackets.
Here we define a list called flowerlist
consisting of items jasmine
, lily
, peony
and tulip
.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
print(flowerlist)
The print()
function above prints the items of the list.
['jasmine', 'lily', 'peony', 'tulip']
Accessing List Items
Index of a list in Python start from 0. Consider the below list. A list element is accessed by passing its index enclosed within a pair the square brackets. For example, the first element of the list can be accesed as flowerlist[0]
.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
print(flowerlist[0])
The print()
function outputs the first element.
jasmine
Negative indices start from -1
, from the last element. The second last item has the index -2
, and so on. Below, flowerlist[-1]
returns the rightmost element tulip
.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
print(flowerlist[-1])
List items can also be sliced within a specified range. To extract items from a list from index 1
to 3
(excluding the item at index 3
), use the expression [1:3] after the list name.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
print(flowerlist[1:3])
Two items from index 1
to 2
are sliced, without the item at index 3
. The following is printed.
['lily', 'peony']
Slicing through the -ve range works the same. Below we slice through the items from index -3
to -1
(excluded).
flowerlist = ["jasmine", "lily", "peony", "tulip"]
print(flowerlist[-3:-1])
The above program prints
['lily', 'peony']
Altering/Changing the Value of a List Item
A list item can be changed/modified by referring to its index. Below we change the item peony
at index 2
to poppy
.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
flowerlist[2] = "poppy"
print(flowerlist)
Length of a List
The length of a list can be determined with the len() function. The below list has four elements, so the print()
function will print out 4.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
print(len(flowerlist))
Looping Through a List
The for in
statement is used for iterating through each element of a list.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
for x in flowerlist:
print(x)
The above loop will print out the following:
jasmine
lily
peony
tulip
Checking If An Item Exists
The if in
statement can be used to check the presence of an element inside a list. The below code prints out lily exists
.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
if "lily" in flowerlist:
print("lily exists")
Sorting a List
Lists in Python can be sorted using the sort()
function. Arguments can be passed to the sort()
function; but if no argument is passed, the list is sorted in ascending order. We consider an unsorted list below.
flowerlist = ["lily", "jasmine", "tulip", "peony"]
flowerlist.sort()
print(flowerlist)
The above print()
function prints out the list which is sorted in ascending order.
['jasmine', 'lily', 'peony', 'tulip']
To sort a list in descending order, pass reverse=True
as an argument to the sort()
function.
flowerlist = ["lily", "jasmine", "tulip", "peony"]
flowerlist.sort(reverse=True)
print(flowerlist)
It prints a list sorted in ascending order.
['tulip', 'peony', 'lily', 'jasmine']
Reversing a List
The reverse()
function reverses a list.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
flowerlist.reverse()
print(flowerlist)
The print()
function above prints the reversed list.
['tulip', 'peony', 'lily', 'jasmine']
Appending/Adding Items to the List
A new item can be appended at the end of the list using the append()
function. Here we append an item zinnia
.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
flowerlist.append("zinnia")
print(flowerlist)
And we get the newly appended list.
['jasmine', 'lily', 'peony', 'tulip', 'zinnia']
If you wish to insert an item at a particluar index, use the insert()
function. Below we insert a new item hyacinth
to the existing list at index 1
.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
flowerlist.insert(1, "hyacinth")
print(flowerlist)
Here is the modified list with a new item inserted at index 1
.
['jasmine', 'hyacinth', 'lily', 'peony', 'tulip']
Deleting/Removing Items from the List
The remove()
function removes a specified item from a given list. Here we remove the item tulip
from the list.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
flowerlist.remove("tulip")
print(flowerlist)
The above print()
function will print the remaining items in the list without the item tulip
.
['jasmine', 'lily', 'peony']
The pop()
function removes an item with a specified index. If the index is not specified, it removes the last element. Here we remove the element with index 1, which is lily
.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
flowerlist.pop(1)
print(flowerlist)
The list is without the lily
item now.
['jasmine', 'lily', 'peony']
Without specifying the index, the pop()
function removes the last element. Here, the item tulip
is removed.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
flowerlist.pop()
There is also the del
statement which can be used the remove a list item by its index. Here we remove the item at index 3, which is tulip
.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
del flowerlist[3]
The del
statement can alo delete an entire list. In the example below, the print()
function throws an error stating that 'flowerlist' is not defined as it is already deleted by the del
statement above it.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
del flowerlist
print(flowerlist)
On the other hand, chaining the clear()
function to a list clears all its items.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
flowerlist.clear()
print(flowerlist)
The program above prints an empty list of square brackets.
[]
Concatenate Two Lists
Two lists can be joined or concatenated using the +
operator. In the program below, newlist
contains the elements of both the lists flowerlist
and anotherlist
.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
anotherlist = ["daffodils", "marigold", "snowdrop"]
newlist = flowerlist + anotherlist
print(newlist)
The print()
method prints the following.
['jasmine', 'lily', 'peony', 'tulip', 'daffodils', 'marigold', 'snowdrop']
Copying a List to Another
The copy() function chained to an existing list returns the shallow copy of a list. We often assign it to a new list.
flowerlist = ["jasmine", "lily", "peony", "tulip"]
anotherlist = flowerlist.copy()
print(anotherlist)
The items of anotherlist
are the same as that of flowerlist
.
['jasmine', 'lily', 'peony', 'tulip']
The List Constructor
A new list can also be created using the list()
constructor.
flowerlist = list(("jasmine", "lily", "peony", "tulip"))
print(flowerlist)
The above print()
function above prints the newly created list.
['jasmine', 'lily', 'peony', 'tulip']