Tristan
0
Q:

python sort list in place

sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
3
# Basic syntax:
your_list.sort()

# Example usage:
your_list = [42, 17, 23, 111]
your_list.sort()
print(your_list)
--> [17, 23, 42, 111]

# If you have a list of numbers that are of type string, you can do the
# following to sort them numerically without first converting to type 
# int. E.g.:
your_list = ['42', '17', '23', '111']
your_list.sort(key=int)
print(your_list)
--> ['17', '23', '42', '111']

# If you want to sort a list of strings in place based on a number 
# that is consistently located at some position in the strings, use
# a lambda function. E.g.:
your_list =['cmd1','cmd10', 'cmd111', 'cmd50', 'cmd99']
your_list.sort(key=lambda x: int(x[3:]))
print(your_list)
--> ['cmd1', 'cmd10', 'cmd50', 'cmd99', 'cmd111']

# If you don't want to sort the list in place, used sorted. E.g.:
your_list = [42, 17, 23, 111]
your_list_sorted = sorted(your_list)
print(your_list_sorted)
--> [17, 23, 42, 111]
1
arr = [ 1, 3, 2]
arr.sort()
1
nums = [4,8,5,2,1]
#1 sorted() (Returns sorted list)
sorted_nums = sorted(nums)
print(sorted_nums)#[1,2,4,5,8]
print(nums)#[4,8,5,2,1]

#2 .sort() (Changes original list)
nums.sort()
print(nums)#[1,2,4,5,8]
3

New to Communities?

Join the community