Python built‑in functions: sorted, eval, and upper – syntax, parameters, and practical examples
This article explains how to use Python's sorted, eval, and upper built‑in functions, covering their syntax, optional arguments such as key, cmp, and reverse, safety considerations for eval, and concrete code examples that demonstrate sorting lists, converting strings to uppercase, and evaluating literals.
The previous chapter introduced dict , filter , and lambda ; this chapter continues with additional functions useful for sorting dictionaries and other data structures.
sorted can sort any iterable. Unlike the list method list.sort() , which modifies the list in place, sorted() returns a new list. Its signature is sorted(iterable[, cmp[, key[, reverse]]]) where:
iterable – the collection to sort.
cmp – a two‑argument comparison function returning 1, -1, or 0.
key – a one‑argument function that extracts a comparison key from each element.
reverse – if True , sort in descending order.
Example using the default behavior:
a = [5, 7, 6, 3, 4, 1, 2]
b = sorted(a) # b is [1, 2, 3, 4, 5, 6, 7]Sorting with a custom cmp function:
L = [('b', 2), ('a', 1), ('c', 3), ('d', 4)]
b = sorted(L, cmp=lambda x, y: cmp(x[1], y[1]))Sorting with a key function:
b = sorted(L, key=lambda x: x[1])Sorting a list of student records by age using key and optionally reverse :
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
sorted_by_age = sorted(students, key=lambda s: s[2])
sorted_desc = sorted(students, key=lambda s: s[2], reverse=True)Using key and reverse together is generally faster than a custom cmp because the key function is called once per element.
eval evaluates a string as a Python expression and returns the result. It can convert string representations of lists, tuples, dictionaries, etc., into actual Python objects:
a = "[[1,2], [3,4], [5,6]]"
b = eval(a) # b becomes [[1, 2], [3, 4], [5, 6]]
print(type(b)) #
c = "{1: 'a', 2: 'b'}"
d = eval(c) # d becomes {1: 'a', 2: 'b'}
print(type(d)) #Because eval executes arbitrary code, it poses serious security risks. Malicious input such as __import__('os').system('dir') can run system commands. Safer alternatives include writing custom validation functions or using ast.literal_eval , which only evaluates Python literals.
upper converts all lowercase letters in a string to uppercase. It takes no arguments and returns a new string:
str = "this is string example from runoob....wow!!!"
print("str.upper() : ", str.upper()) # STR.UPPER() : THIS IS STRING EXAMPLE FROM RUNOOB....WOW!!!The next chapter will cover the hashlib.md5 module.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.