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

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • Variable Length Positional Arguments in Python

    Variable Length Positional Arguments in Python Variable length positional arguments allow a function to accept any number of positional arguments. This is done using the *args syntax. Syntax python def function_name(*args): # function body # args becomes a tuple containing all positional arguments Simple Examples Example 1: Basic *args python def print_numbers(*args): print(“Numbers received:”, args) print(“Type of…

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

  • Real-World Applications of Python Lists

    Python lists and their methods are used extensively in real-time applications across various domains. They are fundamental for organizing and manipulating ordered collections of data. Real-World Applications of Python Lists 1. Web Development In web development, lists are crucial for handling dynamic data. For example, a list can store user comments on a post, products…

  • Password Strength Checker

    python Enhanced Password Strength Checker python import re def is_strong(password): “”” Check if a password is strong based on multiple criteria. Returns (is_valid, message) tuple. “”” # Define criteria and error messages criteria = [ { ‘check’: len(password) >= 8, ‘message’: “at least 8 characters” }, { ‘check’: bool(re.search(r'[A-Z]’, password)), ‘message’: “one uppercase letter (A-Z)”…

Leave a Reply

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