Programming Essentials Python - Overview of Collections - Accessing elements from list

Let us see how we can access elements from the list using Python as a programming language.

  • We can access a particular element in a list by using index l[index]. The index starts with 0.
  • We can also pass index and length up to which we want to access elements using l[index:length].
  • The index can be negative, and it will provide elements from the end. We can get the last n elements by using l[-n:].
  • Let us see a few examples:
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l[0]  # getting the first element
l[2:4]  # get elements from the 3rd up to 4 elements
l[-1]  # get the last element
l[-4:]  # get the last 4 elements
l[-5:-2]  # get elements from the 6th to 8th

Key Concepts Explanation

Indexing in List

Indexing in a list refers to accessing elements based on their position in the list. The index of the first element in a list is 0, the second element is at index 1, and so on. You can access elements using their index like list[index].

Slicing in List

Slicing allows you to create a sublist from a list by specifying a range of indices. The syntax is list[start:end], where elements from the start index up to (but not including) the end index are returned.

Hands-On Tasks

  1. Create a list of your favorite fruits and access the second element from the list.
  2. Take a list of numbers and slice it to get only even numbers from the list.

Conclusion

In this article, we explored how to access elements from a list in Python using indexing and slicing. Practice these concepts to enhance your Python skills and feel free to engage with the community for further learning.

Watch the video tutorial here