The Range Function, Tuples, Unpacking in Python

Day 7 in #100DaysOfCode

The Range Function

We use the range function to generate a sequence of numbers in Python. Here is a small example: Code:

numbers= range(5)
print(numbers)

Result:

range(0, 5)

This is the default representation of the range object. To see the actual numbers we need to iterate over this range object using a for a loop. We can use the for loop with any object that represents a sequence of objects. Code:

numbers= range(5)
for numbers in numbers:
    print(numbers)

Result:

0
1
2
3
4

We can specify two values in the range function; such as range(5, 10). In this case, 10 will be the ending value and it is going to be excluded. Therefore, numbers of 5 to 9 will show up. We can also use three values. In this case, the third number will be used as a step: If we code range(5, 10, 2), we will get 5, 7, and 9.

Tuples

Tuples are used to store multiple items in a single variable. Tuples are immutable. We can't change them once we create them. We use parenthesis to define a tuple. Also, the only methods we can use are "count" and "index". The "Count" method, returns the number of occurrences of an element. The "Index" method is to find out the first occurrence of an item. We use tuples to make sure no one is going to change what we have on the list.

Example:

numbers = (1, 2, 2, 5)

Unpacking

In Python, unpacking is the process of assigning an iterable of values to a tuple (or list) of variables using a single assignment statement.

numbers = (1, 2, 3)
x, y, z = numbers
print(x)

Result:

1