I want to split a list I have of 48 different lengths into a new list for each length of the item. I could do something like
for item in list:
if len(item) == 1:
len1list.append(item)
if len(item) == 2:
len2list.append(item)
etc etc but that would require 48 if statements, just wondering whether there was a more Pythonic way, using less lines of code.
You want to categorize your list based on its items length. So you can sort based on length and group them.You can use
itertools.groupby
for grouping the sub lists (or any iterable object):There is some notes here :
If you don' t want to do operations like indexing or other operations on list, you don't need to convert the result to list (as i have done in above answer) you can let the result to be as a generator that is pretty much efficient for long lists.
If you want more performance in run time you can use dictionaries that use hash-table for storing their data which searching and inserting data has O(1) in them. @junnytony suggested a good way with
defaultdict
. you can also usedict.setdefault
method :