Print Range Values to a Single Line

Introduction:

  • In Python, to print values in a range on a single line, you can iterate over the values using a loop and print them with the print() statement without a newline. Alternatively, you can convert the range into a collection like a list or tuple and print that collection.

Examples:

  1. Print Range in a Single Line using list():
    • In this example, we use the list() built-in function to convert the given range into a list and then print the list. This way, we can print all the values in the range on a single line.

      python
      my_range = range(4, 9)
      my_list = list(my_range)
      print(my_list)
      
    • Output: [4, 5, 6, 7, 8]
       

Exercises:

  1. Print Range Values Using list():
    • Create a range from 5 to 15 and convert it to a list, then print the list on a single line.

      python
      my_range = range(5, 16)
      my_list = list(my_range)
      print(my_list)
      

Summary:

  • In this tutorial, we learned how to print the values of a range object on a single line using a for loop or by converting the range into a list. Practice using these methods to become proficient in working with ranges in your Python programs!