Fundamentals 4 min read

Python Basics: Sorting, Reversing, and Accessing List Elements

This tutorial demonstrates how to sort lists with sort() and sorted(), reverse them, retrieve length, maximum, minimum, and element indices, and includes concrete code examples and their output for each operation.

Lisa Notes
Lisa Notes
Lisa Notes
Python Basics: Sorting, Reversing, and Accessing List Elements

The article introduces common list operations in Python, focusing on sorting, reversing, and retrieving information from lists.

It first explains list.sort(), which sorts the original list in place in ascending order. To sort in descending order, the reverse=True argument is passed. The built‑in sorted() function returns a new sorted list without modifying the original, and it also accepts reverse=True for descending order. Sorting by a custom key, such as the length of string elements, is shown using sorted(list4, key=len).

Reversing a list is performed with the list.reverse() method, which mutates the list in place. The length of a list is obtained via len(list). The maximum and minimum values are retrieved with max(list) and min(list), respectively, and the index of a specific element is found using list.index(value).

list1 = [12, 34, 21, 35, 6, 24]
list1.sort()  # ascending
print(list1)
list1.sort(reverse=True)  # descending
print(list1)
list2 = sorted(list1)  # ascending
print(list2)
list3 = sorted(list1, reverse=True)
print(list3)
list4 = ["abc", "hello", "e", "love", "mm"]
# sort by length of elements
list5 = sorted(list4, key=len)
# print(list5)
list6 = [23, 345, 67, 89, 21]
list6.reverse()
list7 = [32, 4, 54, 5, 7, "hello", True]
# print(len(list7)) #6
list8 = [32, 43, 5454, 65, 789, 43]
print(max(list8))
print(min(list8))
print(list8.index(5454))

The resulting output is:

[6, 12, 21, 24, 34, 35]
[35, 34, 24, 21, 12, 6]
['e', 'mm', 'abc', 'love', 'hello']
6
5454
32
2

These examples illustrate the practical usage of list manipulation functions in everyday Python programming.

Pythonindexlistlenreversesortmaxmin
Lisa Notes
Written by

Lisa Notes

Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.