Skip to Content
Learn
Creating and Modifying a List in Python
Range II

We can use range to generate more interesting lists.

By default, range creates a list starting at 0. However, if we call range with two arguments, we can create a list that starts at a different number. For example, range(2, 9) would generate numbers starting at 2 and ending at 8 (just before 9):

>>> my_list = range(2, 9) >>> print(list(my_list)) [2, 3, 4, 5, 6, 7, 8]

With one or two arguments, range will create a list of consecutive numbers (i.e., each number is one greater than the previous number). If we use a third argument, we can create a list that “skips” numbers. For example, range(2, 9, 2) will give us a list where each number is 2 greater than the previous number:

>>> my_range2 = range(2, 9, 2) >>> print(list(my_range2)) [2, 4, 6, 8]

We can skip as many numbers as we want! In this example, we’ll start at 1 and skip 10 between each number until we get to 100:

>>> my_range3 = range(1, 100, 10) >>> print(list(my_range3)) [1, 11, 21, 31, 41, 51, 61, 71, 81, 91]

Our list stops at 91 because the next number in the sequence would be 101, which is greater than 100 (our stopping point).

Instructions

1.

Modify the range function that created list1 such that it:

  • Starts at 5
  • Has a difference of 3 between each item
  • Ends before 15
2.

Create a range object called list2 that:

  • Starts at 0
  • Has a difference of 5 between each item
  • Ends before 40
Folder Icon

Sign up to start coding

Already have an account?