Python List Indexing

5/5 - (3 votes)

πŸ›‘ Note: Python has zero-based indexing, i.e., the index of the first element is 0, and the index of the i-th element is (i-1). Not considering zero-based indexing but assuming the i-th element has index i is a common source of bugs!

Here’s an example that demonstrates how list indexing works in Python:

squares = [1, 4, 9, 16, 25]

πŸƒ Training Exercise: What is the output of this code snippet?

List Motivation and Definition

The list data structure in Python is super powerful. You have to search very hard to find a Python algorithm that is not built upon a list. Many famous algorithms, such as quicksort, are based on only a single list as a core data structure.

πŸ’‘ Definition: A list is “an abstract data type that represents a countable number of ordered values” — Wikipedia

It is abstract because it is independent of the concrete data type of the values in the list.

Python vs Java Lists

The Python way of handling lists and list access is super simple and clean. Create a list by writing comma-separated values between the opening and closing square brackets.

In the Java programming language, you must use redundant natural language function calls such as get(i) to access a list value. In Python, this is much easier. You access the i-th element in a list l with the intuitive bracket notation l[i]. This notation is consistent for all compound data types such as strings and arrays.

This leads to small and repeated time savings during programming. The time savings of millions of developers add up to a strong collective argument for Python.

Where to Go From Here?

Are you a master coder?
Test your Python skills now!

Related Video

Python Programming Tutorial - 13 - Slicing Lists



Leave a Comment