Really confused about this list exercise I was working on


#1

Here’s the exercise:
Create a function called append_size that has one parameter named lst .

The function should add all of the numbers between 1 and the size of lst (inclusive) to the end of lst . The function should then return this new list.

For example, if lst was [23, 42, 108] , the function should return [23, 42, 108, 1, 2, 3] because the size of lst was originally 3 .

Here was the solution - really not sure what or where the list(range…) came from. I don’t remember ever seeing ‘list’ in any of the steps leading up to this

def append_size(lst):
  to_append = list(range(1, len(lst)+1))
  lst = lst + to_append
  return lst

#2

list() is a constructor from the list class. It takes an iterable such as a string or range and makes it into a list.

That is Python 3. In Python 2, range() returns a list.


#3

ahh - ok thanks man…that’s really helpful to know


#4

Just to ellaborate,

>>> type(range(10))
<class 'range'>
>>> print (range(10))
range(0, 10)
>>> print (list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

whereas in Python 2,

>>> type(range(10))
<class 'list'>
>>> print range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

#5

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