How do you create a tuple with a range of values in Python?

How do you create a tuple with a range of values in Python?

You can create a tuple with a range of values in Python using various techniques. Here are five examples:

  1. Using the range() function and the tuple() constructor:
# Create a tuple with values from 1 to 5
my_tuple = tuple(range(1, 6))
print(my_tuple)  # Output: (1, 2, 3, 4, 5)
  1. Using tuple packing:
# Create a tuple with values 10, 20, and 30
my_tuple = (10, 20, 30)
print(my_tuple)  # Output: (10, 20, 30)
  1. Using a comprehension with the range() function:
# Create a tuple with even numbers from 2 to 10
my_tuple = tuple(x for x in range(2, 11, 2))
print(my_tuple)  # Output: (2, 4, 6, 8, 10)
  1. Using the map() function to apply a function to each element of the range:
# Create a tuple with squares of numbers from 1 to 5
my_tuple = tuple(map(lambda x: x ** 2, range(1, 6)))
print(my_tuple)  # Output: (1, 4, 9, 16, 25)
  1. Using a generator expression:
# Create a tuple with values from 5 to 1 in reverse order
my_tuple = tuple(x for x in range(5, 0, -1))
print(my_tuple)  # Output: (5, 4, 3, 2, 1)

These examples demonstrate different ways to create tuples with a range of values in Python.