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

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

  • re.subn()

    Python re.subn() Method Explained The re.subn() method is similar to re.sub() but with one key difference: it returns a tuple containing both the modified string and the number of substitutions made. This is useful when you need to know how many replacements occurred. Syntax python re.subn(pattern, repl, string, count=0, flags=0) Returns: (modified_string, number_of_substitutions) Example 1: Basic Usage with Count Tracking python import re…

  • Linear vs. Scalar,Homogeneous vs. Heterogeneous 

    Linear vs. Scalar Data Types in Python In programming, data types can be categorized based on how they store and organize data. Two important classifications are scalar (atomic) types and linear (compound) types. 1. Scalar (Atomic) Data Types 2. Linear (Compound/Sequential) Data Types Key Differences Between Scalar and Linear Data Types Feature Scalar (Atomic) Linear (Compound) Stores Single…

  • Formatted printing

    C-Style String Formatting in Python Python supports C-style string formatting using the % operator, which provides similar functionality to C’s printf() function. This method is sometimes called “old-style” string formatting but remains useful in many scenarios. Basic Syntax python “format string” % (values) Control Characters (Format Specifiers) Format Specifier Description Example Output %s String “%s” % “hello” hello %d…

  • append(), extend(), and insert() methods in Python lists

    append(), extend(), and insert() methods in Python lists, along with slicing where applicable. 1. append() Method Adds a single element to the end of the list. Examples: 2. extend() Method Adds multiple elements (iterable items) to the end of the list. Examples: 3. insert() Method Inserts an element at a specific position. Examples: Key Differences: Method Modifies List? Adds Single/Multiple Elements? Position append() ✅ Yes Single element (even if it’s a list) End…

  • Predefined Character Classes

    Predefined Character Classes Pattern Description Equivalent . Matches any character except newline \d Matches any digit [0-9] \D Matches any non-digit [^0-9] \w Matches any word character [a-zA-Z0-9_] \W Matches any non-word character [^a-zA-Z0-9_] \s Matches any whitespace character [ \t\n\r\f\v] \S Matches any non-whitespace character [^ \t\n\r\f\v] 1. Literal Character a Matches: The exact character…

Leave a Reply

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