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

  • Escape Sequences in Python

    Escape Sequences in Python Regular Expressions – Detailed Explanation Escape sequences are used to match literal characters that would otherwise be interpreted as special regex metacharacters. 1. \\ – Backslash Description: Matches a literal backslash character Example 1: Matching file paths with backslashes python import re text = “C:\\Windows\\System32 D:\\Program Files\\” result = re.findall(r'[A-Z]:\\\w+’, text) print(result) #…

  • file properties and methods

    1. file.closed – Is the file door shut? Think of a file like a door. file.closed tells you if the door is open or closed. python # Open the file (open the door) f = open(“test.txt”, “w”) f.write(“Hello!”) print(f.closed) # Output: False (door is open) # Close the file (close the door) f.close() print(f.closed) # Output: True (door is…

  • How to create Class

    🟥 Rectangle Properties Properties are the nouns that describe a rectangle. They are the characteristics that define a specific rectangle’s dimensions and position. Examples: 📐 Rectangle Methods Methods are the verbs that describe what a rectangle can do or what can be done to it. They are the actions that allow you to calculate information…

  • Python Statistics Module

    Python Statistics Module: Complete Methods Guide with Examples Here’s a detailed explanation of each method in the Python statistics module with 3 practical examples for each: 1. Measures of Central Tendency mean() – Arithmetic Average python import statistics as stats # Example 1: Basic mean calculation data1 = [1, 2, 3, 4, 5] result1 = stats.mean(data1) print(f”Mean of…

  • Unlock the Power of Python: What is Python, History, Uses, & 7 Amazing Applications

    What is Python and History of python, different sectors python used Python is one of the most popular programming languages worldwide, known for its versatility and beginner-friendliness . From web development to data science and machine learning, Python has become an indispensable tool for developers and tech professionals across various industries . This blog post…

  • Operator Overloading

    Operator Overloading in Python with Simple Examples Operator overloading allows you to define how Python operators (like +, -, *, etc.) work with your custom classes. This makes your objects behave more like built-in types. 1. What is Operator Overloading? 2. Basic Syntax python class ClassName: def __special_method__(self, other): # Define custom behavior 3. Common Operator Overloading Methods Operator…

Leave a Reply

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