Help Understanding


#1

So this code works and all but I am having trouble understanding part of it. I don't understand the significance of square_list = [] specifically the [] part
Other than that, I understand everything. Thank you


start_list = [5, 3, 1, 2, 4]
square_list =[]
for number in start_list:
    square_list.append(number**2)
square_list.sort()

print square_list


#2

[] is the symbolic representation of a list. (list class) when it is not prefixed with an identifier. In that case it would be symbolic of a subscript, a sequential integer index.

Let's see,

>>> isinstance([], list)
True

Being as a list is iterable, it will have a length property.

>>> len([])
0

As above illustrated, the list class has an append method, among many other ways to query and modify a list object. It is not uncommon to see a variable declared and initialized as an empty list.

my_list = []

In your program above a static list is iterated and the square of each value is appended to the working list, the outcome of which should ultimately be,

[ 1, 4, 9, 16, 25 ]

#3

List build up:

>>> lst = []          # Start as an empty list
>>> lst.append('a')   # Use append() to add elements
>>> lst.append('b')
>>> print(lst)
['a', 'b']

Hope that helps.


#4

Thank you guys. Understand it now :slight_smile:


#5

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