Built-in functions / commands for Lists

Built-in functions / commands for Lists

·

1 min read

Why Lists?

There are many data types in python and each of them has a unique trait. Like dictionaries, specialized in storing specific data under specific names, tuples, which are immutable, sets, which can sort out the commonalities between another set. For to see, lists seem like the dullest and boring data type out of all of them. However, lists are just so flexible and have innumerable possibilities. This article is about a few commands you can use to quickly edit lists and sort them out.

Declaration

f_list = ['orange', 'banana', 'mango', 'papaya', 'apple', 'pineapple', 'lemon', 'strawberry']

sort vs. sorted

Sorted : sorts the list according to the condition and returns a NEW object different from the input.

Sort : sorts the ORIGINAL list and alters the input list.

Sorted Conditions

print('sorted - ', sorted(f_list)) # default : alphabetical, numerical
print('sorted - ', sorted(f_list, reverse=True))
print('sorted - ', sorted(f_list, key=len)) # length of the word
print('sorted - ', sorted(f_list, key=lambda x: x[-1]))
print('sorted - ', sorted(f_list, key=lambda x: x[-1], reverse=True))

Sort Conditions

print('sort - ', f_list.sort(), f_list)
print('sort - ', f_list.sort(reverse=True), f_list)
print('sort - ', f_list.sort(key=len), f_list)
print('sort - ', f_list.sort(key=lambda x: x[-1]), f_list)