l=[[1,4],
[2,7],
[10,1],
[1,2],
[10,6],
[2,1]]
print(sorted(l,key=lambda x: (x[0],x[1]))) # use lambda to sort by "x[0]"-> first element of the sublists or x[1] -> second element, if its a tie
[[1, 2], [1, 4], [2, 1], [2, 7], [10, 1], [10, 6]]

Or simply sorted(l) of l.sort() as your elements sort naturally.

A better example would be to sort by the second value only:

print(sorted(l,key=lambda x: (x[1])))
[[10, 1], [2, 1], [1, 2], [1, 4], [10, 6], [2, 7]]
Answer from Padraic Cunningham on Stack Overflow
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Sort a 2D List in Python | note.nkmk.me
July 27, 2023 - To do this, you can use list comprehension to apply sorted() to each list. ... l_2d = [[20, 3, 100], [1, 200, 30], [300, 10, 2]] pprint.pprint(l_2d, width=20) # [[20, 3, 100], # [1, 200, 30], # [300, 10, 2]] pprint.pprint([sorted(l) for l in ...
Discussions

python - sort a 2D list first by 1st column and then by 2nd column - Stack Overflow
I am trying to find a nice way to sort a 2d list , first by the 1st value , and then by the 2nd value. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Sorting 2D List in Python - Stack Overflow
Any elements in lists have to be separated by commas. Please don't use list as a variable as it is an inbuilt function ... Take a look at the 'sorted' builtin function and, in particular, the [optional] 'key' named parameter More on stackoverflow.com
๐ŸŒ stackoverflow.com
How would you sort a 2D list by row based on the first column using a separate list as a key
If you want to sort it by month, why not use a dictionary of lists, such that dict['Nov'] = [0.0, 0.0, 0.09, etc.]? More on reddit.com
๐ŸŒ r/learnpython
3
1
November 22, 2022
python - How can I sort a 2D list? - Stack Overflow
I'm working with a 2D list of numbers similar to the example below I and am trying to reorder the columns: D C B A 1 3 2 0 1 3 2 0 1 3 2 0 The first row of the list is reserved for letters to More on stackoverflow.com
๐ŸŒ stackoverflow.com
January 17, 2016
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to sort by the second element in a 2d list
r/learnpython on Reddit: How to sort by the second element in a 2D list
February 20, 2021 - The sort function (of course) needs values to compare, so when it scans through the list, the values it โ€œseesโ€ correspond to L[1] for each sublist L, i.e. the numbers in your 2D list. As you noted, without that key function the list-to-list comparison is essentially just a lexicographical sort by the first element, unless thereโ€™s a tie, in which case it looks at the number. ... Starting learning Python at 50.
๐ŸŒ
Statistics Globe
statisticsglobe.com โ€บ home โ€บ python programming language for statistics & data science โ€บ sort 2d list in python (2 examples)
How to Sort 2D Python List | Order 2 Dimensional Array Elements
June 1, 2023 - For instance, to sort a 2D list based on the first element of each sublist, we defined the lambda function as lambda x: x[0]. The sorted() function and the sort() method are both used to sort elements in a list in Python, but they have some ...
๐ŸŒ
Script Everything
scripteverything.com โ€บ posts โ€บ how to sort 2d array in python: 1 line of code without numpy
How To Sort 2D Array In Python: 1 Line Of Code Without Numpy | Script Everything
July 29, 2021 - To sort a two-dimensional list ... in Python, without using any imported libraries, use the built-in sort() list method and sorted() function. By using the built-in sort list method you can mutate the original list to your desired requirements, whereas by using the sorted function it will return ...
๐ŸŒ
YouTube
youtube.com โ€บ watch
Sorting two dimensional lists in Python - YouTube
How to sort 2d list by the second or third sub item in a lists. Great for making high score tables.
Published: January 16, 2017
Find elsewhere
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ sort 2d array python
How to Sort 2D Array in Python | Delft Stack
February 2, 2024 - from operator import itemgetter lst = [ ("john", "C", 15), ("jane", "A", 12), ("dave", "D", 10), ] sorted_lst = sorted(lst, key=itemgetter(1)) print(sorted_lst) ... Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe ... Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language.
๐ŸŒ
YouTube
youtube.com โ€บ script everything
Sort 2D List By Multiple Columns Using Python - YouTube
How do you sort a 2D list in Python?Using the sorted() function and the key parameter you can use a lambda function that takes a tuple of the elements you wa...
Published: December 7, 2022
Views: 352
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how would you sort a 2d list by row based on the first column using a separate list as a key
r/learnpython on Reddit: How would you sort a 2D list by row based on the first column using a separate list as a key
November 22, 2022 -

so i have a data set of rain data over the course of a year where it ends up being formatted into something like this except its a lot longer

[['Nov', 0.0], ['Nov', 0.0], ['Nov', 0.09],['Feb', 0.0], ['Feb', 0.0], ['Feb', 0.09],['Oct', 0.56], ['Oct', 0.0], ['Oct', 0.03], ['Oct', 0.62]]

now I figured I would need another list to function as a lookup to help sort this data by month according to calendar order so I made one

month_lookup = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

but now I am a tad confused about how I would go about using something like the sorted() function to use the lookup as the way to sort the 2D list above

๐ŸŒ
Codecademy Forums
discuss.codecademy.com โ€บ data science
Is there a way to sort a two-dimensional list on the values of the second 'column'? - Data Science - Codecademy Forums
September 25, 2023 - For example, in the Python Lists Project, I have created a two-dimensional list by joining the names and insurance costs, in that order. Is it possible to sort the list by the insurance cost? Thanks ๐Ÿ™‚ link: https://www.codecademy.com/journeys/data-scientist-ml/paths/dsmlcj-22-data-science-foundations/tracks/dsmlcj-22-python-fundamentals-for-data-science-part-i/modules/dsf-python-lists-0fe2ec39-68f4-4899-975a-71e76552d627/projects/ds-python-lists2-project
๐ŸŒ
University of Kentucky
cs.uky.edu โ€บ ~keen โ€บ 115 โ€บ lectures โ€บ sort-by-any-column.html
Untitled
from random import randint # Demonstrates sorting 2-dimensional lists by any column # the get_item function should return the element in the desired column # the only purpose of this function is to return the 2nd element in the # 1-dimensional list that is the parameter def get_item(lst): return lst[1] def main(): # building a list of 8 rows which have 2 random numbers each mylst = [] for i in range(8): mylst.append( [randint(10,50), randint(100, 200)] ) print("Original list", mylst) print("\nSorted by first column, ascending order", sorted(mylst) ) # sorted by first column print("\nSorted by first column, descending order", sorted(mylst, reverse = True)) print("\n\nSorted by second column, ascending order", sorted(mylst, key=get_item)) print("\nSorted by second column, descending order", sorted(mylst, key=get_item, reverse = True)) print("\nOriginal list unchanged", mylst) main()
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-21310.html
sorting 2D lists by column
September 24, 2019 - Hello everyone, I would like to sort a multidimensional list by the second column. Example: x = [ [1,18,2], [2,9,4], [3,1,1] ] x = sorted(x, key=lambda x: x[2]) print(x)The output I am looking for should be: [ [3,1,1], [2,9,4], [1,...
๐ŸŒ
Mrgoff
mrgoff.com โ€บ py_lists
Python toolbox MrGoff.com
The first command here would clear the sub-list in position 1 i.e. the second sub-list. This would leave the scores list as [[15,19,22],[],[7,12,9],[15,18,12]]. The second clear command would leave an empty one-dimensional list. Lambda sorting can allow us to sort a 2D list based on the value in a certain position in each sub-list.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 62395588 โ€บ sort-2d-list-in-ascending-order
python - Sort 2D list in ascending order - Stack Overflow
@yatu--you're right. I place the key automatically since I forget that sort automatically sort lists that way by default. ... Their is this function in python called sorted. It is an amazing thing you know, we all love it. It basically sorts any list you give it.
Top answer
1 of 6
45

How does your "2D array" look like?

For example:

>>> a = [
     [12, 18, 6, 3], 
     [ 4,  3, 1, 2], 
     [15,  8, 9, 6]
]
>>> a.sort(key=lambda x: x[1])
>>> a
[[4,  3,  1, 2], 
 [15, 8,  9, 6], 
 [12, 18, 6, 3]]

But I guess you want something like this:

>>> a = [
     [12, 18, 6, 3], 
     [ 4,  3, 1, 2], 
     [15,  8, 9, 6]
]
>>> a = zip(*a)
>>> a.sort(key=lambda x: x[1])
>>> a
[(6,  1,  9), 
 (3,  2,  6), 
 (18, 3,  8), 
 (12, 4, 15)]
>>> a = zip(*a)
>>> a
[(6, 3, 18, 12), 
 (1, 2,  3,  4), 
 (9, 6,  8, 15)
]
2 of 6
23

Python, per se, has no "2d array" -- it has (1d) lists as built-ins, and (1d) arrays in standard library module array. There are third-party libraries such as numpy which do provide Python-usable multi-dimensional arrays, but of course you'd be mentioning such third party libraries if you were using some of them, rather than just saying "in Python", right?-)

So I'll assume that by "2d array" you mean a list of lists, such as:

lol = [ range(10), range(2, 12), range(5, 15) ]

or the like -- i.e. a list with 3 items, each item being a list with 10 items, and the "second row" would be the sublist item lol[1]. Yeah, lots of assumptions, but your question is so maddeningly vague that there's no way to avoid making assumptions - edit your Q to clarify with more precision, and an example!, if you dislike people trying to read your mind (and probably failing) as you currently make it impossible to avoid.

So under these assumptions you can sort each of the 3 sublists in the order required to sort the second one, for example:

indices = range(10)
indices.sort(key = lol[1].__getitem__)
for i, sublist in enumerate(lol):
  lol[i] = [sublist[j] for j in indices]

The general approach here is to sort the range of indices, then just use that appropriately sorted range to reorder all the sublists in play.

If you actually have a different problem, there will of course be different solutions;-).

๐ŸŒ
Codefinity
codefinity.com โ€บ courses โ€บ v2 โ€บ 4f4826d5-e2f8-4ffd-9fd0-6f513353d70a โ€บ a4da9564-36a0-4109-b920-88fc7b89ddbb โ€บ e919a538-f041-447b-8082-e453a3c2aa5b
Learn Sorting 2D Arrays | Commonly used NumPy Functions
12345678 import numpy as np array_2d ... in descending order along a given axis, you need to use two slices: one full slice ([:]) and another with a negative step ([::-1])....