-1

In the listRange part if I use [(range(1, num +1)], instead of list(range(1, num+1)), The program doesn't work why ?

num = int(input("Please choose a number to divide: "))

listRange = list(range(1,num+1))

divisorList = []

for number in listRange:
    if num % number == 0:
        divisorList.append(number)

print(divisorList)
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Gaurav
  • 1
  • 1
  • 3
    Have you tried using the interactive mode, and try e.g. `[range(1, 5)]`? What do you get? How does it differ from `list(range(1, 5))`? – Some programmer dude Sep 13 '17 at 07:59
  • 3
    Possible duplicate of [mylist = list() vs mylist = \[\] in Python](https://stackoverflow.com/questions/11780357/mylist-list-vs-mylist-in-python) – Sayse Sep 13 '17 at 08:01
  • ^See duplicate answer - "The list() built-in is useful to convert some other iterable to a list" – Sayse Sep 13 '17 at 08:02
  • I got unsupported operand type if I use [range (1, num + 1)], but I get the desired solution if I use range(1, num + 1) or list(range(1, num +1)) – Gaurav Sep 13 '17 at 08:03

2 Answers2

1

In Python 3, range() returns a range object.

With list(...) you're converting the range object (which is an iterable) to a list. With [] you're wrapping the range object in a list, w/o iterating the content.

print([(range(1))]) # [range(0, 1)]
print(list(range(1))) # [0]
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
  • Thank you so much...I just joined today and you guys replied within a minute...this is so cool. – Gaurav Sep 13 '17 at 08:10
0

as an additional option you can 'unpack' the range object with the asterisk/star(some call it "splat") operator

[*range(7)]
Out[213]: [0, 1, 2, 3, 4, 5, 6]
f5r5e5d
  • 3,656
  • 3
  • 14
  • 18