Python From Beginner to Advanced

0% completed

Previous
Next
Python - Accessing Elements in a List

Lists in Python allow direct access to elements using indexing. Indexing helps retrieve individual elements based on their position in the list. Python provides two types of indexing:

  • Positive Indexing: Starts from 0 for the first element, 1 for the second, and so on.
  • Negative Indexing: Starts from -1 for the last element, -2 for the second-last, and so on.

Additionally, Python allows accessing a range of elements using slicing and provides a way to check whether an element exists in a list.

Accessing Elements Using Positive Indexing

In positive indexing, elements are counted from left to right, starting from 0.

Example

Python3
Python3

. . . .

Explanation

  1. fruits[0] retrieves "Apple", the first element.
  2. fruits[1] retrieves "Banana", the second element.
  3. fruits[2] retrieves "Cherry", the third element.
  4. fruits[3] retrieves "Date", the fourth element.

Accessing Elements Using Negative Indexing

In negative indexing, elements are counted from right to left, starting from -1.

Example

Python3
Python3

. . . .

Explanation

  1. fruits[-1] retrieves "Date", the last element.
  2. fruits[-2] retrieves "Cherry", the second last element.
  3. fruits[-3] retrieves "Banana", the third last element.
  4. fruits[-4] retrieves "Apple", the fourth last element.

Checking if an Element Exists in a List

To check whether an element exists in a list, use the in keyword.

Example

Python3
Python3

. . . .

Explanation

  1. "Cat" in animals returns True because "Cat" is in the list.
  2. "Lion" in animals returns False because "Lion" is not in the list.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next