List slicing Codeacademy vs Pycharm question


#1



https://www.codecademy.com/courses/python-beginner-en-KAgt5/2/4


No errors


The same in pycharm

I get the list slicing thing. when i do this in codeacademy :

to_one_hundred = range(101)
# Add your code below!

backwards_by_tens = to_one_hundred[::-10]
print (backwards_by_tens)

It gives me the right answer in code academy. But when i do this in pycharm. it gives me:

range(100, -1, -10)

my pycharm is working with python 3.0. But i cant find if there is any difference..
Can someone help me?


#2

the problem is in range(), from here:
In Python versions before 3, range() creates a list, as you say. In Python 3, it creates a generator

so the problem is in this line:

to_one_hundred = range(101)

we can see this, if we do in python2:

to_one_hundred = range(101)
print to_one_hundred

and in python3:

to_one_hundred = range(101)
print(to_one_hundred)

we see a list in python2, and a generator in python3. you could solve this problem by forcing python3 to use a list:

to_one_hundred = list(range(101))

or use list comprehension.


#3

Actually, range objects are sequences, while generators can merely be queried for the next value until exhausted


#4

Ah i see now, thanks for your help guys and explanations.


#5

i should really double check my sources.

@tent, good to hear you solved the issue :slight_smile:


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.