Python Tutorial

Accessing Elements From Python List

How to Access Elements From a List in Python?

The items in the list are indexed, and you can find them by looking up the index number: 

Example:

Print the second item of the list:

thislist = ["pear", "melon", "orange"]

print(thislist[1])

Output:

melon
  • Negative Indexing

Negative indexing in Python indicates that you should begin from the end. -1 denotes the last item, -2 the second last item, and so on.

Example: 

Print the last item of the list:

thislist = ["pear", "melon", "orange"]

print(thislist[-1])

Output:

orange
  • Range of Indexes

You can provide a range of indices by indicating where the range begins and ends.
When you specify a range, the result is a new list with the items you specified.

Example:

Return the third, fourth, and fifth item:

thislist = ["pear", "melon", "orange", "orange", "avacado", "melon", "mango"]

print(thislist[2:5])

Output:

orange, melon
  • Range of Negative Indexes

If you wish to start searching from the bottom of the list, use negative indexes:

Example: 

thislist = ["pear", "melon", "orange", "orange", "avacado", "melon", "mango"]

print(thislist[-4:-1])

Output:

['orange', 'avacado', 'melon']
  • Check if Item Exists

Make use of the in keyword to check if a certain item is contained in a list:

Example: 

Check if "pear" is present in the list:

thislist = ["pear", "melon", "orange"]

if "pear" in thislist:

  print("Yes, 'pear' is in the fruits list")

Output: 

Yes, 'pear' is in the fruits list
Did you find this article helpful?