Sort and Copy List

Sort and Copy List

Instructor-svgAl-Mamun Sarkar
Apr 11 , 2021

Sometimes we need to sort the list and need to create a new copy of the list. We can sort the list using the sort() method and copy a list using the copy() method. 

 

Sorting a List using sort() method:

numbers = [23, 12, 54, 3, 2, 6, 11, 9, 7, 8]
numbers.sort()
print(numbers)

Output:

[2, 3, 6, 7, 8, 9, 11, 12, 23, 54]

 

 Sorting a List in reverse order:

numbers = [23, 12, 54, 3, 2, 6, 11, 9, 7, 8]
numbers.sort(reverse=True)
print(numbers)

Output:

[54, 23, 12, 11, 9, 8, 7, 6, 3, 2]

Sort in Descending Order:

 

If we need a new sorted list but the main list will be unsorted then we can do that using the sorted() function:

numbers = [23, 12, 54, 3, 2, 6, 11, 9, 7, 8]
sorted_numbers = sorted(numbers)
print(numbers)
print(sorted_numbers)

Output:

[23, 12, 54, 3, 2, 6, 11, 9, 7, 8]
[2, 3, 6, 7, 8, 9, 11, 12, 23, 54]

Sort in Descending order:

numbers = [23, 12, 54, 3, 2, 6, 11, 9, 7, 8]
sorted_numbers = sorted(numbers, reverse=True)
print(numbers)
print(sorted_numbers)

Output:

[23, 12, 54, 3, 2, 6, 11, 9, 7, 8]
[54, 23, 12, 11, 9, 8, 7, 6, 3, 2]


 

Copy a List:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
new_list = numbers.copy()

Copy Using list() constructor:

numbers = ['one', 'two', 'three', 'four', 'fine', 'six']
new_list = list(numbers)

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram