Data Types - range() Flashcards

1
Q

What is the syntax for range()

A

range(start, stop, step)

Same as with slicing, except use commas rather than colons - [start : stop : step]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What if you only specify 1 number in range()

A

Stop value

The number range will start with (& include) index ‘0’ and end at index n-1 i.e., range(3) will end at index ‘2’

range(start, stop, step)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What if you specify 2 numbers in range() seperated by a comma

A

Start then Stop values

The number range will start with (& include) index [first number] and end at index n-1 [n=second number] i.e., range(2, 5) will start at index ‘2’ and end at index ‘4’

range(start, stop, step)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

for i in range(1, 21, -1):
print(i)

What does the above print

A

Nothing…

Below is a corrected version to print a reversed range

for i in range(20, 0, -1):
print(i)

It causes confusion trying to produce a reversed range like this. To avoid confusion, it’s best practice to use reversed(range(1, 21))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

for i in range(21):
print(i)

What is the clearest way to write the above range of numbers in reverse

A

for i in reversed(range(1, 21)):
print(i)

for i in range(20, 0, -1) causes more confusion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly