Jose Ramon
Jose Ramon

Reputation: 5444

Check if the lengths inside a nested list are identical

I have a list of lists and I want to calculate first the size of each sub-list and then to see whether all those sub-lists have size 2. Therefore,

my_list = [["obj1", "item1"], ["obj2", "item2", "item1"], ["obj3", "item3"], ["obj4", "item4"], ["obj5", "item5"]]
lengths = [len(x) for x in my_list]

The list lengths contains the size of each sub-list. How can I check whether all my sub-lists have size two or not? In my example it should fail.

Upvotes: 1

Views: 1502

Answers (4)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15568

You could do it in one line:

print(all(map(lambda x:len(x)==2, my_list)))

First I map an on-fly function that check if the length is two. Then I apply all that returns True if all values are True, else False.

In production code, you could use assert

assert all(map(lambda x:len(x)==2, my_list)), 'Not all have length 2'

Results: enter image description here

Upvotes: 0

Srce Cde
Srce Cde

Reputation: 1824

Using all() and map(). Mapping len with my_list to find length of the sub-list.

my_list = [["obj1", "item1"], ["obj2", "item2", "item1"], ["obj3", "item3"], ["obj4", "item4"], ["obj5", "item5"]]
all(i == 2 for i in map(len, my_list))

Output:

False

If you want to check all the length is identical.

my_list = [["obj1", "item1"], ["obj2", "item2"], ["obj3", "item3"], ["obj4", "item4"], ["obj5", "item5"]]
len(set(list(map(len, my_list)))) <=1 

Output:

True

Upvotes: 0

Chris Mueller
Chris Mueller

Reputation: 6680

You can identify the number of unique elements in a list by converting it to a set. If the length of the set is 1, and the only element of the set is 2, then you know that every list had length 2.

my_list = [["obj1", "item1"], ["obj2", "item2", "item1"], ["obj3", "item3"], ["obj4", "item4"], ["obj5", "item5"]]
lengths = [len(x) for x in my_list]

print(set(lengths))
# {2, 3}

len(set(lengths)) == 1 and set(lengths).pop() == 2
# False

Upvotes: 1

timgeb
timgeb

Reputation: 78690

Use all with a generator expression.

>>> my_list = [[1, 2], [3, 4], [5]]
>>> all(len(sub) == 2 for sub in my_list)
False
>>> 
>>> my_list[-1].append(6)
>>> all(len(sub) == 2 for sub in my_list)
True

Or if the length does not have to be two specificly:

>>> subs = iter(my_list)
>>> len_ = len(next(subs))
>>> all(len(sub) == len_ for sub in subs)
True

Upvotes: 3

Related Questions