Numerical Lists

Counting at the speed of light!

The range() function.

The range() function allows you to print a sequence of numbers with a given step size (default = 1). Notice that the list stops before the 2nd argument.

range(start,stop,step)

              # Range function with a the default step-size of 1
              for value in range(1,5):
                print(value)
            

              1
              2
              3
              4
            

Different Step Size

You can define a specific step-size to create more interesting sequences of numbers.


                # Print all even numbers from 1-10
                for value in range(1,11,2):
                  print(value)
              

                1
                3
                5
                7
                9
              

List of Numbers

You can also make a range of numbers into a list by calling the list() function. You can then use any of the list methods such as sort() to manipulate your list.


              # Make a list of numbers from 1-4
              numbers = list(range(1,5))
                print(numbers)
            

              [1, 2, 3, 4]
            

Generating Custom Sequences

You are not just limited to counting by an integer step-size. You can specify an expression to generate almost any sequences imaginable:


              # Create an empty list
              squares = []
              # For loop to generate integers from 1 to 10
              for value in range(1,11):
              # Append the square of the integer in value to the List
                squares.append(value**2)
              # Print the list
              print(squares)
            

              [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
            

Simple Stats with Number Lists

You can use the min(), max() and sum() functions to get the minimum, maximum and sum of all the numbers in a list respectively


            digits = [1,2,3,4,5,6,7,8,9,0]
            # Find minimum, maximum and total sum of the digits list
            print(min(digits))
            print(max(digits))
            print(sum(digits))
          

            0
            9
            45
          

List Comprehensions

The program used to create the sequence of perfect square numbers in previous slide in three lines but with a list comprehension you can do all three steps in one line.


          # Build a list of the first 10 perfect square numbers
          squares = [value**2 for value in range(1,11)]
          print(squares)
          

            [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]