Python - Built in Functions Part 4: Iterable and Sequence Manipulation Functions
These functions work with collections like lists, tuples, and dictionaries.
Common Functions:
len(): Returns the length of an iterable.
sum(): Calculates the sum of elements in an iterable.
sorted(): Returns a sorted version of an iterable.
reversed(): Returns a reversed iterator.
enumerate(): Adds an index to elements of an iterable.
Examples:
Calculate the length of a list:
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # Output: 3
Sort a list of numbers:
nums = [5, 2, 9, 1]
print(sorted(nums)) # Output: [1, 2, 5, 9]
Enumerate items in a list:
for index, fruit in enumerate(fruits):
print(index, fruit)
# Output:
# 0 apple
# 1 banana
# 2 cherry
Explanation:
Functions like len() and sorted() are indispensable for analyzing and organizing data. These functions allow for quick operations like finding the size of a dataset, reordering items, or attaching indices for structured access.