Count sub_lists length in python3
<p>My python is 3 ver.
I have a list, which contains sub lists, like:</p>

<pre><code>L=[[1,2], [3,4], [5,6,7]]
</code></pre>

<p>I want to calculate length of all sub_list and write down them to a dictionary, like this:</p>

<pre><code>D={2:2,3:1}
</code></pre>

<p>that is, we have 2 lists which have length 2, and 1 list which have the length 3.</p>

<p>It can be done by for-loop + check D[key] is exist or not.</p>

<p>May be there is some 'pythonic way?'</p>

<p>Use <code>defaultdict</code> where you store the length of the list as the key, and just increment each value by 1 every time to get a matching list length:</p>

<pre><code>from collections import defaultdict

d = defaultdict(int)
L = [[1,2], [3,4], [5,6,7]]

for li in L:
    d[len(li)] += 1

print(d) # defaultdict(&lt;class 'int'&gt;, {2: 2, 3: 1})
</code></pre>

<p>Or use <code>Counter</code> from <code>collections</code> as well:</p>

<pre><code>from collections import Counter

c = Counter(len(li) for li in L)

print(c) # Counter({2: 2, 3: 1})
</code></pre>

python python-3.x