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

Python 3 list behavior

I was practicing python and found the below behaviour and I failed to understand why. Can someone explain why?

Case 1

a = [[] for i in range(5)]
b = [[]] * 5
a[3].append(3)
b[3].append(3)
print(a) # Output: [[], [], [], [3], []]
print(b) # Output: [[3], [3], [3], [3], [3]]

I see different behavior on a and b, what’s the difference between a and b?

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

Case 2

def test(sentences):
    root = {}
    for sentence in sentences:
        base = root
        for word in sentence.split(' '):
            if not base.get(word):
                base[word] = {}
            base = base[word]
    return root

print(test(["Hello world", "Hello there"]))
# Output: {'Hello': {'world': {}, 'there': {}}}

Maybe a noob question but In Case 2 when you’re not modifying root how is it getting modified?

>Solution :

* operation on list will be creating duplicates of one list. Here is the proof,

In [1]: a = [[] for i in range(5)]
   ...: b = [[]] * 5

In [2]: [id(i) for i in a]
Out[2]: [4649788160, 4640976128, 4647308224, 4647305856, 4643089472]

In [3]: [id(i) for i in b]
Out[3]: [4648966336, 4648966336, 4648966336, 4648966336, 4648966336]

Same for happening for case2 as well.

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