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

  • 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…

  • start(), end(), and span()

    Python re start(), end(), and span() Methods Explained These methods are used with match objects to get the positional information of where a pattern was found in the original string. They work on the result of re.search(), re.match(), or re.finditer(). Methods Overview: Example 1: Basic Position Tracking python import re text = “The quick brown fox jumps over the lazy…

  • What is general-purpose programming language

    A general-purpose programming language is a language designed to be used for a wide variety of tasks and applications, rather than being specialized for a particular domain. They are versatile tools that can be used to build anything from web applications and mobile apps to desktop software, games, and even operating systems. Here’s a breakdown…

  • Type Conversion Functions

    Type Conversion Functions in Python 🔄 Type conversion (or type casting) transforms data from one type to another. Python provides built-in functions for these conversions. Here’s a comprehensive guide with examples: 1. int(x) 🔢 Converts x to an integer. Python 2. float(x) afloat Converts x to a floating-point number. Python 3. str(x) 💬 Converts x…

  • Default Arguments

    Default Arguments in Python Functions Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead. Basic Syntax python def function_name(parameter=default_value): # function body Simple Examples Example 1: Basic Default Argument python def greet(name=”Guest”): print(f”Hello, {name}!”)…

  • The print() Function in Python

    The print() Function in Python: Complete Guide The print() function is Python’s built-in function for outputting data to the standard output (usually the console). Let’s explore all its arguments and capabilities in detail. Basic Syntax python print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Arguments Explained 1. *objects (Positional Arguments) The values to print. You can pass multiple items separated by commas. Examples:…

Leave a Reply

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