简体   繁体   中英

Length of a single sublist in python

Lets assume i have a list of 3 sublists

a = [[1,1,1],[1,1,1],[1,1,1]]

If I use the command len(a[0:2]) I get the answer 2 (Because there are two elements(sublists) in the list)

But when I do len(a[2]) and want to get the answer 1 (because there is only one element(sublist) in the list) I actually get the length of the third list (which is 3 in this case).

How could I solve this problem?

You have to specify the range you want to look at.

len(a[1:2]) should do the trick.

len(a[x:y]) simply means "the length of a from element x to y (non-inclusive)"

So if you do len(a[2:2]) the output is 0.

You can use:

print(len(a[2:3]))

Or if want it builtin, do a function:

_len=len
def len(l):
    if _len(l)==0:
        return 0
    elif isinstance(l[0],list):
        return _len(l)
    return _len([l])

a=[[1,1,1],[1,1,1],[1,1,1]]
print(len(a[2]))

Both Output:

1

You need to use len(a[2:3]) :

 a = [[1,2,3],[4,5,6],[7,8,9]]

a[2]
>>> [7, 8, 9] 

len(a[2])
>>> 3

a[2:3]
>>> [[7, 8, 9]] 

len(a[2:3])
>>> 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM