I have been pracising list slicing using the range() with python 3 but wheneve I type list=[start:end:stride] python 3 won't print the list as expected.
I expect it to print the list of values according to instructions given by list slicing code.For instance in the code below I expect it to print a list of [,9,7,5,3] but instead it brings "[range(1,11)]". Why is this so with python 3 yet with python 2 it works perfectly
Python 3 has a range type that you will need to convert to a list. See below ...
my_list = range(1, 11) # create a range
backwards_sequence = my_list[::-2] # reverse the range and skip alternate items
print(type(backwards_sequence)) # show us that it is a range and not yet a list
backwards = list(backwards_sequence) # convert the range to a list
print(type(backwards)) # now we have a list
... and that is perhaps the most beautiful part of this story. The Python community is very clever, and is always coming up with new ways to improve the Python language. To store a list of 1000000000 items, you store all 1000000000 items. But to store a range of any number of items, the only information you need to store is the start, end, and stride values.
For a range that might include a billion values, that is a great advantage over a list.
First, you create a range that includes all the integers from 1 to 10, inclusive. Since 11 was the end value, it was not included.
my_list = range(1, 11)
Then you reverse the order of the integers, and skip every other one, with your stride being -2.
Now, with the order reversed, 0 is the exclusive end value, so that the range stops without including 0. The result is a range that begins at 10 and descends with stride of -2 to an end value of 0. So you get this ...
Basically, the reason why the stop value of the reversed range is 0 rather than 1 is that when we defined the original range, we used a start value of 1, which is inclusive. When we reverse the range, the system uses the original start value to compute the new stop value. Since the stop value is exclusive, the system goes past the start value by 1 when computing the new stop value to guarantee that the original start value will be included in the new range, if the step value allows it. Because we are now using a negative step, going past the start value by 1 means subtracting 1 from the original start value to get the new stop value. The absolute value of the step does not matter when computing the new stop value; rather it is the sign of the step that matters, which is negative in this case.
Although a stop value of either 0 or 1 would have given us the same output, the most elegant policy is for the system to simply go 1 past the original start value to create the new stop value. It will always include the correct values in the new range.