Say you have a list of lists, so for example:
my_list = [[1, "foo"], [2, "bar"], [1, "dog"], [2, "cat"], [1, "fox"],
[1, "jar"], [2, "ape"], [2, "cup"], [2, "gym"], [1, "key"]]
and you wanted to create (in this case two, but could be more) two new distinct lists depending on the first element of each list in my_list
, how would you do this?
Of course you could do something like:
new_list1 = []
new_list2 = []
for item in my_list:
if item[0] == 1:
new_list1.append(item)
else:
new_list2.append(item)
so
new_list1 = [[1, "foo"], [1, "dog"], [1, "fox"], [1, "jar"], [1, "key"]]
new_list2 = [[2, "bar"], [2, "cat"], [2, "ape"], [2, "cup"], [2, "gym"]]
but that is really specific and not very nice in my opinion, so there must be a better way to do this.