Home >Backend Development >Python Tutorial >How to get the length of a list in Python? (code example)
Lists are an integral part of daily programming in Python, and it is essential to understand the related operations of lists. The following article will show you how to get the length of a list in Python. I hope it will be helpful to you.
Method 1: Loop Counter
In this method, just run a loop and increment Counter, until the last element of the list is traversed, its count is obtained, which is the length of the list. This method is the most basic way to get the length of a list.
Code example: Using a loop to traverse the counter to get the list length
# 初始化列表 List = [ 1, 4, 5, 7, 8 ] # 输出列表 print ("列表为: " + str(List)) # 初始化计数器,使用循环查找列表长度 counter = 0 for i in List: #递增计数器 counter = counter + 1 # 输出列表长度 print ("列表长度为: " + str(counter))
Output:
##Method 2: Use len()
Python len() method to return the length or number of items of an object (character, list, tuple, etc.). It provides the most common and simplest way to find the length of any list; it is also the most common technique employed today.Code example: Use the len() method to get the list length
Example 1:# 初始化列表 List = [ "php", "python", 3, 7,"html" ] List.append(6) List.append("Hello") # 输出列表 print ("列表为: " + str(List)) # 输出列表长度 print ("列表长度为: " ,len(List))Output: Example 1:
n = len([10, 20, 30]) # 输出列表长度 print ("列表长度为:" ,n)Output:
列表长度为:3
Method 3: Using length_hint()
Code example: Use the length_hint() method to get the list length
from operator import length_hint # 初始化列表 List = [ 1, 4, 5, 7, 8 ] # 输出列表 print ("列表为: " + str(List)) list_len_hint =length_hint(List) # 输出列表长度 print ("列表长度为: " + str(list_len_hint))Output:
Python Tutorial"
The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !The above is the detailed content of How to get the length of a list in Python? (code example). For more information, please follow other related articles on the PHP Chinese website!