This article introduces the len() function in Python in detail, covering the following aspects:
Basics of len() function:
- len() is a built-in function in Python, used to return the number of items contained in an object, and can be used on a variety of built-in data types (such as strings, lists, tuples, dictionaries, collections, etc.) as well as some third-party types (such as NumPy arrays, Pandas' DataFrame).
- Use len() for built-in types is more direct, and can be implemented by custom classes.lenThe () method extends its support for len(), and the len() function is mostly run with O(1) time complexity, which gets the result by accessing the object's length attribute.
- Data types such as integers, floating point numbers, booleans, complex numbers, etc. cannot be used as parameters of len(). Using inapplicable data types as parameters will raise a TypeError, and iterators and generators cannot be used directly for len().
Examples of usage in different built-in data types:
- Built-in sequences: Built-in sequences such as strings, lists, tuples, range objects, etc. can all be obtained by len(), and empty sequences can be returned by 0 using len().
>>> greeting = "Good Day!" >>> len(greeting) 9 >>> office_days = ["Tuesday", "Thursday", "Friday"] >>> len(office_days) 3 >>> london_coordinates = (51.50722, -0.1275) >>> len(london_coordinates) 2 >>> len("") 0 >>> len([]) 0 >>> len(()) 0
- Built-in collection: The number of unique elements in a sequence such as a list can be obtained through the collection. When the dictionary is used as a parameter, len() returns the number of its key-value pairs, and when the empty dictionary and empty set are cooperated with the parameters of len() returns 0. >>> import random
>>> numbers = [(1, 20) for _ in range(20)] >>> numbers [3, 8, 19, 1, 17, 14, 6, 19, 14, 7, 6, 1, 17, 10, 8, 14, 17, 10, 2, 5] >>> unique_numbers = set(numbers) >>> unique_numbers {1, 2, 3, 5, 6, 7, 8, 10, 14, 17, 19} >>> len(unique_numbers) 11
Common usage examples:
- Verify the user input length: Use the if statement combined with len() to determine whether the user name entered by the user is within the specified range.
username = input("Choose a username: [4-10 characters] ") if 4 <= len(username) <= 10: print(f"Thank you. The username {username} is valid") else: print("The username must be between 4 and 10 characters long")
- End the loop based on object length: For example, collecting a certain number of valid user names, using len() to determine whether the loop continues, it can also be used to determine whether the sequence is empty, but sometimes using the sequence itself to determine the authenticity of the sequence itself will be more Pythonic.
usernames = [] print("Enter three options for your username") while len(usernames) < 3: username = input("Choose a username: [4-10 characters] ") if 4 <= len(username) <= 10: print(f"Thank you. The username {username} is valid") (username) else: print("The username must be between 4 and 10 characters long") print(usernames)
- Find the index of the last item of the sequence: generate a random number sequence and obtain the index of the last element after certain conditions are met. Although it can be calculated by len(), there are more Pythonic methods, such as using index -1, etc.
>>> import random >>> numbers = [] >>> while sum(numbers) <= 21: ... ((1, 10)) ... >>> numbers [3, 10, 4, 7] >>> numbers[len(numbers) - 1] 7 >>> numbers[-1] # A more Pythonic way to retrieve the last item 7 >>> (len(numbers) - 1) # You can use (-1) or () 7 >>> numbers [3, 10, 4]
- The split list is two parts: use len() to calculate the list length and find the midpoint index to divide the list. If the number of list elements is odd, the lengths of the two parts of the split result will be different.
>>> import random >>> numbers = [(1, 10) for _ in range(10)] >>> numbers [9, 1, 1, 2, 8, 10, 8, 6, 8, 5] >>> first_half = numbers[: len(numbers) // 2] >>> second_half = numbers[len(numbers) // 2 :] >>> first_half [9, 1, 1, 2, 8] >>> second_half [10, 8, 6, 8, 5]
Use in third-party libraries:
- NumPy's ndarray: After installing NumPy, you can create arrays of different dimensions. For two-dimensional and multi-dimensional arrays, len() returns the size of the first dimension (such as a two-dimensional array returns the number of rows). You can obtain the size of each dimension of the array through the .shape attribute and use .ndim to obtain the number of dimensions.
>>> import numpy as np >>> numbers = ([4, 7, 9, 23, 10, 6]) >>> type(numbers) <class ''> >>> len(numbers) 6 >>> numbers = [ [11, 1, 10, 10, 15], [14, 9, 16, 4, 4], [28, 1, 19, 7, 7], ] >>> numbers_array = (numbers) >>> numbers_array array([[11, 1, 10, 10, 15], [14, 9, 16, 4, 4], [28, 1, 19, 7, 7]) >>> len(numbers_array) 3 >>> numbers_array.shape (3, 5) >>> len(numbers_array.shape) 2 >>> numbers_array.ndim 2
- Pandas' DataFrame: After installing pandas, you can create a DataFrame from the dictionary. len() returns the number of rows of DataFrame, which also has the .shape attribute that reflects the rows and columns.
>>> import pandas as pd >>> marks = { "Robert": [60, 75, 90], "Mary": [78, 55, 87], "Kate": [47, 96, 85], "John": [68, 88, 69], } >>> marks_df = (marks, index=["Physics", "Math", "English"]) >>> marks_df Robert Mary Kate John Physics 60 78 47 68 Math 75 55 96 88 English 90 87 85 69 >>> len(marks_df) 3 >>> marks_df.shape (3, 4)
- Use in user-defined classes: It can be implemented when defining classes.lenThe () method customizes the length meaning of the object so that this class of objects can be used as a parameter of len(), and at the same time.lenThe () method must be a non-negative integer.
class DataFrame(NDFrame, OpsMixin): # ... def __len__(self) -> int: """ Returns length of info axis, but here we use the index. """ return len()
Attachment: Example
Calculate the length of the string:
>>> s = "hello good boy doiido" >>> len(s) 21
Calculate the number of elements in the list:
>>> l = ['h','e','l','l','o'] >>> len(l) 5
Calculate the total length of the dictionary (i.e. the total number of key-value pairs):
>>> d = {'num':123,'name':"doiido"} >>> len(d) 2
Calculate the number of tuple elements:
>>> t = ('G','o','o','d') >>> len(t) 4
Summarize
This is the article about the usage examples of the len() function in Python. For more information about the usage content of Python len() function, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!