Python 3 – List len() Method
In Python, lists are one of the most commonly used data structures. They allow you to store multiple items in a single variable, which can then be accessed and manipulated as needed. One common operation you may need to perform on a list is to determine its length – that is, how many items it contains. For this purpose, Python provides the len()
method, which can be called on any list to obtain its length.
Syntax
The syntax for using the len()
method on a list is simple. All you need to do is call the method on the list itself, like so:
myList = [1, 2, 3, 4, 5]
print(len(myList))
This code creates a list containing the numbers 1 through 5, then calls the len()
method on it to determine its length. The result is 5, which is printed to the console.
Example
Here is another example that demonstrates how you can use the len()
method with a more complex list:
myList = ["apple", "banana", "cherry", "date", "elderberry"]
print(len(myList))
In this code, we create a list of fruit names and then call len()
on it. The result is 5, which is printed to the console.
Using len()
in Loops
Another common use for the len()
method is when iterating over a list with a loop. In this case, we can use the length of the list to determine how many times to loop. Here is an example:
myList = ["John", "Jane", "Bob", "Alice", "Mary"]
for idx in range(len(myList)):
print(myList[idx])
In this code, we first create a list of names. We then use the range()
function along with len()
to create a loop that will iterate the same number of times as the length of the list. Within the loop, we use the loop variable idx
to index into the list and print each name.
Conclusion
The len()
method is a useful tool for working with lists in Python. By calling this method on a list, you can quickly determine how many items it contains. This can be helpful when dealing with large or complex lists, and is often used in combination with loops to perform various operations on the list’s items. Overall, the len()
method is a simple yet powerful feature of Python’s list data structure that every programmer should be familiar with.