Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting python list to make letters come before numbers

Tags:

People also ask

How do you sort letters and numbers in Python?

Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

How do I sort a list into numerical order in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.

How do you sort letters in a list in Python?

To sort a list alphabetically in Python, use the sorted() function. The sorted() function sorts the given iterable object in a specific order, which is either ascending or descending. The sorted(iterable, key=None) method takes an optional key that specifies how to sort.


I'm pretty new to python and I'm looking for a way to sort a list placing words before numbers.

I understand you can use sort to do the following :

a = ['c', 'b', 'd', 'a']
a.sort()
print(a)
['a', 'b', 'c', 'd']

b = [4, 2, 1, 3]
b.sort()
print(b)
[1, 2, 3, 4]

c = ['c', 'b', 'd', 'a', 4, 2, 1, 3]
c.sort()
print(c)
[1, 2, 3, 4, 'a', 'b', 'c', 'd']

However I'd like to sort c to produce :

['a', 'b', 'c', 'd', 1, 2, 3, 4]

Thanks in advance