In this Python article, we will take a deep dive into the Python List len() method – a powerful and handy technique for returning the number of items.
We will cover its syntax, usage, and explore some examples to better understand its practical applications.
List len() method in Python
Below are the topics that we are doing to discuss in this article:
- Introduction to Python List len() method
- Syntax of the len() method
- Purpose and use cases of the len() method
Python List len() method
The len() method is a built-in Python function that returns the number of items in a given iterable, such as a list, tuple, or string. It is a simple yet powerful method that aids in various tasks, from basic data manipulation to complex data analysis.
The syntax for the len() method is as follows:
len(iterable)
Where iterable
is the input Python list, tuple, or string whose length we want to find. The function returns an integer representing the number of elements in the iterable.
len() method in Python List Examples
Let’s dive into some examples to better understand the len() method in action:
Example#1 Basic Usage
# Define a list of US state abbreviations
state_abbreviations = ['AL', 'AK', 'AZ', 'AR', 'CA']
# Get the length of the list
length = len(state_abbreviations)
print(length)
In this example, we have a Python list of US state abbreviations containing five elements. The len() method returns the number of abbreviations in the Python list, which is 5.
Output:
Example#2 Nested Lists
# Define a nested list of cities in three states
cities_by_state = [['New York', 'Los Angeles', 'Chicago'], ['Houston', 'Phoenix', 'Philadelphia'], ['San Antonio', 'San Diego', 'Dallas']]
# Get the length of the list
length = len(cities_by_state)
print(length)
Here, we have a nested Python list containing cities from three different states. Each sublist represents a state, and the Python len() method returns the number of top-level elements in the Python list, which is the number of states (sublists) themselves, in this case, 3.
Output:
Example#3 Empty List
# Define an empty list for US Presidents
us_presidents = []
# Get the length of the empty list
length = len(us_presidents)
print(length)
In this example, we have an empty Python list for storing US Presidents. Since there are no elements in the list, the len() method returns 0.
Output:
Example#4 Strings and Tuples
# Define a string of US Presidents and a tuple of state capitals
us_presidents = "Washington, Adams, Jefferson, Madison, Monroe"
state_capitals = ('Montgomery', 'Juneau', 'Phoenix', 'Little Rock', 'Sacramento')
# Get the lengths
presidents_length = len(us_presidents)
capitals_length = len(state_capitals)
print(presidents_length)
print(capitals_length)
In this example, we have a string containing US Presidents separated by commas and a tuple of state capitals. The Python len() method returns the number of characters in the string, which is 41, and the number of elements in the tuple, which is 5.
Output:
Note: In the case of the string, the len() method counts the commas and spaces as characters.
len() method use cases in Python List
Let’s dive into some use cases of the Python List len() method:
Example#1 Conditionally executing code based on the length of a list
# List of some popular US cities
cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix']
# Check if the list has more than 3 cities
if len(cities) > 3:
print("This is a long list of cities.")
else:
print("This is a short list of cities.")
Here, we have a Python list of popular US cities. We use the len() method to determine if the Python list has more than three cities. If it does, we print “This is a long list of cities.” Otherwise, we print “This is a short list of cities.”
Output:
Example#2 Calculating the percentage of a specific element in a list
# List of state bird names, with some repeats
state_birds = ['Cardinal', 'Mockingbird', 'Mockingbird', 'Robin', 'Cardinal', 'Goldfinch', 'Mockingbird']
# Calculate the percentage of Mockingbirds in the list
mockingbird_count = state_birds.count('Mockingbird')
total_birds = len(state_birds)
percentage = (mockingbird_count / total_birds) * 100
print(f"The percentage of Mockingbirds in the list is {percentage}%.")
In this example, we have a Python list of state bird names. We want to calculate the percentage of Mockingbirds in the list. We count the number of Mockingbirds using the count()
method and divide it by the total number of birds using the len() method, then multiply the result by 100 to get the percentage.
Output:
Example#3 Determining if a list is empty or not
# List of some US national parks
national_parks = ['Yellowstone', 'Yosemite', 'Grand Canyon', 'Zion']
# Check if the list is empty
if len(national_parks) == 0:
print("The list of national parks is empty.")
else:
print("The list of national parks is not empty.")
In this example, we have a Python list of US national parks. We use the len() method to check if the list is empty. If the length of the list is 0, we print “The list of national parks is empty.” Otherwise, we print “The list of national parks is not empty.”
Output:
Conclusion
The Python List len() method is an essential tool for working with Python lists and other iterable data types. It provides a simple and efficient way to determine the number of elements in an iterable, enabling developers to perform various tasks, from basic data manipulations to complex data analyses.
You may like to read the following articles:
- Python List sort() method [With Examples]
- How to Convert a List of Characters into a String in Python
- Python dictionary values to list – Helpful tutorial
- Check if a list exists in another list Python
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.