Python: How do u organize a list based on its first element without hardcoding it?
Kavin1983

How would you organize a list of list based on its first element without hardcoding the list length or the value of the element?

ex:

my_list = [[28,34,6], [28,23,5], [29,78,4], [29,56,4],[30,23,6],[30,34,4]]

list_for28 = [elements that have the 0th value of 28]
list_for29 = [elements that have the 0th value of 29]
list_for30 = [elements that have the 0th value of 30]

i've been dealing with this problem for quite a while and not hardcoding it is very difficult for me.

You are viewing a single comment. View All
OldWizard209

This is very simple. First, you create an empty list for list_for28, list_for29, list_for30. Then you create a for loop that iterates over my_list, and if the 0th index of my_list has 28,29 or 30 you append it to the respective list. Le Code:

Le Output:

:P ;) :D

Kavin1983

@OldWizard209 thanks but the thing is I’m using a api and the 0th value will be changing every day.

OldWizard209

so you will need to modify the if statement to something that will first see the first value of each list and then compare... @Kavin1983