0

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.

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

you can try this also

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.