Home > Back-end >  Defining a Nested List Function for Counting Numbers of Lists and Elements in Python
Defining a Nested List Function for Counting Numbers of Lists and Elements in Python

Time:08-17

I am trying to define a function that takes nested lists and outputs:

(1) How many lists are in the list,

and (2) Whether the number of elements in each list are the same.

I have two nested lists:

nl1: [[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 4, 6, 8, 10]]

nl2: [[1, 2, 3, 4, 5], [3, 4, 6, 7], [2, 4, 6, 8, 10]]

the function name is nlc() nested list count

nl1 = [[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 4, 6, 8, 10]]

nl2 = [[1, 2, 3, 4, 5], [3, 4, 6, 7], [2, 4, 6, 8, 10]]

def nlc(n):

    sl = len(n)

    print("Number of Lists is", sl)

    for list in n:
        r = list(map(len, n))
        if r ==list()
        print("Lengths Match")
        else print("Lengths Not Equal; Check Lists")

Two things:

(P1) Python keeps returning an error saying that r = list(map(len, n)) is wrong because it is a string.

(P2) I can't seem to figure out how to write the code that checks whether each nested list has the same number of elements.

Moreover, when I test P1, it runs just fine:

nl1 = [[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 4, 6, 8, 10]]

r = list(map(len, nl1))

print(r)

So I am not sure what's happening to the argument with I am defining the function.

CodePudding user response:

I suppose you are using list() built-in method and also using it as a variable in a loop, this is causing an error. You can do the same task as this

#Function definition
def nlc(n):
    '''It checks how many lists are in the list, and whether the number of elements in each list are the same.'''
    sl = len(n)
    print("Number of Lists is", sl)
    lengths = []
    for element in n: 
        lengths.append(len(element))          #appending length of each sublist
    if len(set(lengths)) == 1:                #checking if all elements are same in a list. It means that all lengths are equal
        print("Lengths Match")
    else:
        print("Lengths Not Equal; Check Lists")

nl1 = [[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 4, 6, 8, 10]]
nl2 = [[1, 2, 3, 4, 5], [3, 4, 6, 7], [2, 4, 6, 8, 10]]
nlc(nl2)

CodePudding user response:

nl1 = [[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 4, 6, 8, 10]]
nl2 = [[1, 2, 3, 4, 5], [3, 4, 6, 7], [2, 4, 6, 8, 10]]

def nlc(n):
    
    sl = len(n)
    print(f"Number of Lists is {sl}")
    
    r = set(map(len, n))
    if len(r) == 1:
        print("Lengths Match")
    else:
        print("Lengths Not Equal; Check Lists")

nlc(nl1)
  • Related