简体   繁体   中英

what is the meaning of yh = [ [ ] ] * num in python

what is the meaning of yh = [ [ ] ] * num in python. and list in a list? is it mean when num = 3 yh = [ [[]],[[]],[[]] ]? the full code down below to calculate an Pascal's triangle.

def main():
    num = int(input('Number of rows: '))
    yh = [[]] * num
    for row in range(len(yh)):
        yh[row] = [None] * (row + 1)
        for col in range(len(yh[row])):
            if col == 0 or col == row:
                yh[row][col] = 1
            else:
                yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]
            print(yh[row][col], end='\t')
        print()


if __name__ == '__main__':
    main()

[[]] is a list containing a single empty list.

List multiplication creates a new list with the same elements repeated that number of times. So [[]] * num will create a list of num elements in length, where each element is the same empty list. That's generally unlikely to be what you want - because all the elements refer to the same list any mutations you apply to it will be seen in all places. In this example it doesn't matter - the code never accesses those items. You could do [None] * num instead and the code still works.

For an example of the hazards here, consider this example:

>>> sequence = [[]] * 3
>>> print(sequence)
[[], [], []]
>>> sequence[0].append(77)
>>> print(sequence)
[[77], [77], [77]]

This is the much the same as if you'd done:

>>> empty = []
>>> sequence = [empty, empty, empty]
>>> print(sequence)
[[], [], []]
>>> empty.append(33)
>>> print(sequence)
[[33], [33], [33]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM