1

I have a list assigned to the variable my_list.

my_list = [[(1, 2)], [(4, 8), (2, 3)], [(1, 6), (6,7), (8,9)]]. 

I need to find the length of my_list, but len(my_list) only returns 3.

I want it to return 6. I am new to python. Is there any Python function that will return the full length of my_list including the nested lists?

4 Answers 4

2

There's no built in function like that, but you can get it easily with a generator expression:

length = sum(len(inner_list) for inner_list in my_list)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use itertools.chain.from_iterable.

my_list  = [[(1, 2)], [(4, 8), (2, 3)], [(1, 6), (6,7), (8,9)]]
length = len(list(itertools.chain.from_iterable(my_list)))
print(length)
# >>> 6

Edit: If you have to do this a lot, and don't want to type len(list(itertools.chain.... each time, you can create your own function.

def my_len(arr):
    return len(list(itertools.chain.from_iterable(arr)))

Then call my_len on any list of lists you need the length of.

my_list  = [[(1, 2)], [(4, 8), (2, 3)], [(1, 6), (6,7), (8,9)]]
print(my_len(my_list))
# > 6

Comments

0

Flatten the list:

my_list  = [[(1, 2)], [(4, 8), (2, 3)], [(1, 6), (6,7), (8,9)]];
flat = [item for sublist in my_list  for item in sublist];
print (len(flat));

Comments

0

this should work:

sum(len(x) for x in mylist)

basically its doing a little

loop over the elements of "mylist". len(mylist) gives 3 because obviously there are 3 elements in this "outer" list

. The lists nested inside each have their own number of elements, the sum function is just an easy way to run a counter over these elements.

sorry for my very blasphemous explanation, I am not a by programmer by training.

edit: i see someone has already posted this above

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.