← Back to all posts
##### Python: How do u organize a list based on its first element without hardcoding it?

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.

hotnewtop
OldWizard209 (1631)

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:

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

list_for28 = []
list_for29 = []
list_for30 = []

for i in my_list:
if i[0] == 28:
list_for28.append(i)
if i[0] == 29:
list_for29.append(i)
if i[0] == 30:
list_for30.append(i)

print("List containing 28 as first value: {}\nList containing 29 as first value: {}\nList containing 30 as first value: {}".format(list_for28, list_for29, list_for30))``````

Le Output:

``````List containing 28 as first value: [[28, 34, 6], [28, 23, 5]]
List containing 29 as first value: [[29, 78, 4], [29, 56, 4]]
List containing 30 as first value: [[30, 23, 6], [30, 34, 4]]``````

# :P ;) :D

Kavin1983 (1)

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

OldWizard209 (1631)

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