Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[]] 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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading