Iteration & Sequence Functions 

1. sorted()

Description: Returns a new sorted list from the items in iterable.

python

# 1. Sort list of numbers
numbers = [3, 1, 4, 1, 5, 9, 2]
print(sorted(numbers))          # [1, 1, 2, 3, 4, 5, 9]

# 2. Sort list of strings
fruits = ["banana", "apple", "cherry"]
print(sorted(fruits))           # ['apple', 'banana', 'cherry']

# 3. Reverse sort
print(sorted(numbers, reverse=True))  # [9, 5, 4, 3, 2, 1, 1]

# 4. Sort tuple
tup = (5, 2, 8, 1)
print(sorted(tup))              # [1, 2, 5, 8]

# 5. Sort string (returns list of characters)
word = "python"
print(sorted(word))             # ['h', 'n', 'o', 'p', 't', 'y']

# 6. Sort by key (string length)
words = ["cat", "elephant", "dog"]
print(sorted(words, key=len))   # ['cat', 'dog', 'elephant']

# 7. Sort by absolute value
numbers = [-5, 3, -1, 4, -2]
print(sorted(numbers, key=abs)) # [-1, -2, 3, 4, -5]

# 8. Sort dictionary keys
d = {"b": 2, "a": 1, "c": 3}
print(sorted(d))                # ['a', 'b', 'c']

# 9. Sort with custom key (last character)
words = ["apple", "banana", "cherry"]
print(sorted(words, key=lambda x: x[-1]))  # ['banana', 'apple', 'cherry']

# 10. Sort mixed types (raises error)
mixed = [1, "a", 2]
# sorted(mixed) would raise TypeError

2. reversed()

Description: Returns a reverse iterator.

python

# 1. Reverse list
lst = [1, 2, 3, 4]
print(list(reversed(lst)))      # [4, 3, 2, 1]

# 2. Reverse string
s = "hello"
print(''.join(reversed(s)))     # 'olleh'

# 3. Reverse tuple
tup = (1, 2, 3)
print(tuple(reversed(tup)))     # (3, 2, 1)

# 4. Reverse range
r = range(5)
print(list(reversed(r)))        # [4, 3, 2, 1, 0]

# 5. Use in for loop
for num in reversed([1, 2, 3]):
    print(num)                  # 3, 2, 1

# 6. Reverse and convert to list
numbers = [5, 2, 8, 1]
reversed_list = list(reversed(numbers))
print(reversed_list)            # [1, 8, 2, 5]

# 7. Reverse string characters
word = "python"
reversed_chars = list(reversed(word))
print(reversed_chars)           # ['n', 'o', 'h', 't', 'y', 'p']

# 8. Reverse bytes
b = bytes([1, 2, 3])
print(bytes(reversed(b)))       # b'\x03\x02\x01'

# 9. Multiple reversals
lst = [1, 2, 3]
rev1 = list(reversed(lst))
rev2 = list(reversed(rev1))
print(rev2)                     # [1, 2, 3]

# 10. Reverse empty iterable
print(list(reversed([])))       # []

3. slice()

Description: Returns a slice object for slicing sequences.

python

# 1. Basic slicing
lst = [0, 1, 2, 3, 4, 5]
s = slice(2, 5)
print(lst[s])                   # [2, 3, 4]

# 2. Slice with step
s = slice(1, 6, 2)
print(lst[s])                   # [1, 3, 5]

# 3. Slice from start
s = slice(3)
print(lst[s])                   # [0, 1, 2]

# 4. Slice to end
s = slice(2, None)
print(lst[s])                   # [2, 3, 4, 5]

# 5. Negative slicing
s = slice(-3, -1)
print(lst[s])                   # [3, 4]

# 6. Slice string
text = "hello world"
s = slice(6, 11)
print(text[s])                  # 'world'

# 7. Slice with all parameters
s = slice(1, 8, 3)
numbers = list(range(10))
print(numbers[s])               # [1, 4, 7]

# 8. Slice tuple
tup = (0, 1, 2, 3, 4, 5)
s = slice(1, 4)
print(tup[s])                   # (1, 2, 3)

# 9. Reuse slice object
s = slice(0, 3)
lst1 = [1, 2, 3, 4, 5]
lst2 = [10, 20, 30, 40, 50]
print(lst1[s], lst2[s])         # [1, 2, 3] [10, 20, 30]

# 10. Slice with None values
s = slice(None, None, 2)
print(lst[s])                   # [0, 2, 4]

4. iter()

Description: Returns an iterator object.

python

# 1. Create iterator from list
lst = [1, 2, 3]
it = iter(lst)
print(next(it))                 # 1
print(next(it))                 # 2
print(next(it))                 # 3

# 2. Iterator from string
s = "hi"
it = iter(s)
print(list(it))                 # ['h', 'i']

# 3. Iterator from tuple
tup = (1, 2, 3)
it = iter(tup)
print(next(it))                 # 1

# 4. Iterator from range
r = range(3)
it = iter(r)
print(list(it))                 # [0, 1, 2]

# 5. Use in for loop (implicit)
it = iter([1, 2, 3])
for item in it:
    print(item)                 # 1, 2, 3

# 6. Iterator from dictionary keys
d = {"a": 1, "b": 2}
it = iter(d)
print(list(it))                 # ['a', 'b']

# 7. Iterator from set
my_set = {1, 2, 3}
it = iter(my_set)
print(next(it))                 # 1 (order may vary)

# 8. Exhausted iterator
it = iter([1, 2])
print(next(it))                 # 1
print(next(it))                 # 2
# next(it) would raise StopIteration

# 9. Iterator from bytes
b = bytes([65, 66, 67])
it = iter(b)
print(bytes(it))                # b'ABC'

# 10. Multiple iterators from same list
lst = [1, 2, 3]
it1 = iter(lst)
it2 = iter(lst)
print(next(it1), next(it2))     # 1, 1

Bonus: Combined Examples

python

# Combined: sorted + reversed
numbers = [3, 1, 4, 1, 5]
sorted_reversed = list(reversed(sorted(numbers)))
print(sorted_reversed)          # [5, 4, 3, 1, 1]

# Combined: slice + sorted
lst = [5, 2, 8, 1, 9, 3]
s = slice(1, 5, 2)
sorted_slice = sorted(lst)[s]
print(sorted_slice)             # [2, 5]

# Combined: iter + slice
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = slice(2, 8, 2)
it = iter(numbers[s])
print(list(it))                 # [2, 4, 6]

# Combined: all functions
data = [9, 1, 5, 3, 7, 2, 8, 4, 6]
# Sort, reverse, take slice, create iterator
result = iter(reversed(sorted(data))[2:6])
print(list(result))             # [7, 6, 5, 4]

These functions are essential for working with sequences and iterables in Python, providing powerful ways to manipulate and traverse data!

Similar Posts

  • Decorators in Python

    Decorators in Python A decorator is a function that modifies the behavior of another function without permanently modifying it. Decorators are a powerful tool that use closure functions. Basic Concept A decorator: Simple Example python def simple_decorator(func): def wrapper(): print(“Something is happening before the function is called.”) func() print(“Something is happening after the function is…

  • Anchors (Position Matchers)

    Anchors (Position Matchers) in Python Regular Expressions – Detailed Explanation Basic Anchors 1. ^ – Start of String/Line Anchor Description: Matches the start of a string, or start of any line when re.MULTILINE flag is used Example 1: Match at start of string python import re text = “Python is great\nPython is powerful” result = re.findall(r’^Python’, text) print(result) #…

  • Global And Local Variables

    Global Variables In Python, a global variable is a variable that is accessible throughout the entire program. It is defined outside of any function or class. This means its scope is the entire file, and any function can access and modify its value. You can use the global keyword inside a function to modify a…

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

Leave a Reply

Your email address will not be published. Required fields are marked *