Convert Range into a Set


Convert Range into a Set

To convert a given range object into a Set in Python, you can use set() builtin function. Call the set() function and pass the given range object as argument. The set() function creates a new set using the values from the given range object, and returns it.

The syntax to convert given range object myrange into a set myset is

myset = set(myrange)

Examples

1. Convert range(start, stop) into a set

In the following example, we take a range object with a start of 4, and stop of 10, and convert this range object into a set.

Python Program

# Take a range
myrange = range(4, 10)
# Convert range object into a set
myset = set(myrange)
print(myset)

Output

{4, 5, 6, 7, 8, 9}

2. Convert range(start, stop, step) into a set

In the following example, we take a range object with a specific step value, and convert this range object into a set.

Python Program

# Take a range
myrange = range(4, 15, 2)
# Convert range object into a set
myset = set(myrange)
print(myset)

Output

{4, 6, 8, 10, 12, 14}

Summary

In this tutorial of Python Ranges, we learned how to convert a range object into a Set of integers using set() builtin function.