🛑 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] print(squares)
🏃 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!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.