如何获取Python列表中的元素数量?
在本文中,我们将讨论如何获取Python列表中的元素数量。
例子:
Input: [1,2,3,4,5]
Output:
No of elements in the list are
5
Input: [1.2 ,4.5, 2.2]
Output:
No of elements in the list are
3
Input: [“apple”, “banana”, “mangoe”]
Output:
No of elements in the list are
3
在获取Python列表中的元素数量之前,我们必须创建一个空列表。创建空列表后,我们必须将项目或元素插入列表中。有两种方法可以获取列表中元素的数量,即,
- 使用 Len( )函数
- 使用 for 循环
使用 Len()函数
我们可以使用 len函数,即 len() 来返回列表中存在的元素数
Python3
# Returning the number of elements using
# len() function in python
list = [] # declare empty list
# adding items or elements to the list
list.append(1)
list.append(2)
list.append(3)
list.append(4)
# printing the list
print(list)
# using the len() which return the number
# of elements in the list
print("No of elements in list are")
print(len(list))
Python3
# Python Program for returning the number
# of elements in the list using for loop
list = [] # declaring empty list
# inserting elements in the list using
# append method
list.append(1)
list.append(2)
list.append(3)
list.append(4)
# declaring count variable as integer to keep
# track of the number of elements in for loop
count = 0
# for loop for iterating through each element
# in the list
for i in list:
# increments count variable for each
# iteration
count = count+1
# prints the count variable i.e the total number
# of elements in the list
print(list)
print("No of elements in the list are")
print(count)
输出
[1, 2, 3, 4]
No of elements in list are
4
使用 for 循环
我们可以声明一个计数器变量来使用 for 循环计算列表中元素的数量,并在循环终止后打印计数器。
蟒蛇3
# Python Program for returning the number
# of elements in the list using for loop
list = [] # declaring empty list
# inserting elements in the list using
# append method
list.append(1)
list.append(2)
list.append(3)
list.append(4)
# declaring count variable as integer to keep
# track of the number of elements in for loop
count = 0
# for loop for iterating through each element
# in the list
for i in list:
# increments count variable for each
# iteration
count = count+1
# prints the count variable i.e the total number
# of elements in the list
print(list)
print("No of elements in the list are")
print(count)
输出
[1, 2, 3, 4]
No of elements in the list are
4
因此,通过这种方式,我们可以在Python使用 for 循环返回列表的元素数。