Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

Simple code to understand in order to solve a hackerrank challenge

Hello hackforums coders,

I'm trying to solve a challenge on HackerRank. The challenge is more complex. But here is a small piece of code. I have the feeling that understanding this could allow me to understand more complex things.
Code
a = []
c = [0]
c[0]=1
a.append(c)
print(a)
c[0]=2
a.append(c)
print(a)

b=[]
b.append([1])
print(b)
b.append([2])
print(b)


Here is the result in the console:

[[1]]
[[2], [2]]
[[1]]
[[1], [2]]

Normally, the two small pieces of code should produce the same outputs. But in one case, it gives me [[2], [2]], and in the other, it gives me [[1], [2]]. For me, [[1], [2]] is correct.
[Image: Azythum.png]
It might have something to do about the fact that when you append c to a, it actually creates a sort of link to the value of c. Where in the first case c[0] was set to 1. And this value was appended to a. Now in the next step we overwrite the value of c[0] to 2 and add it to a again. Now we might be able to refer to the list a, as: [c[0], c[0]]. Now because we changed c[0] to 2, it simply fills this last value in to the list of a, rather than putting in the values as copies of c[0].
(Aug 2, 2024 08:53 AM)Perlo Wrote:  It might have something to do about the fact that when you append c to a, it actually creates a sort of link to the value of c. Where in the first case c[0] was set to 1. And this value was appended to a. Now in the next step we overwrite the value of c[0] to 2 and add it to a again. Now we might be able to refer to the list a, as: [c[0], c[0]]. Now because we changed c[0] to 2, it simply fills this last value in to the list of a, rather than putting in the values as copies of c[0].

Ok thanks very much for answering. I think i understand!
[Image: Azythum.png]
(Aug 2, 2024 09:24 AM)Azythum Wrote:  Ok thanks very much for answering. I think i understand!

No problem! Glad to hear that it helped you out. If you need more assistance feel free to contact me.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by MelonbreadHFNov 4, 2018 01:44 AM 0 161 Nov 4, 2018 01:44 AM
Last Post: MelonbreadHF
[Python] by CrypticXNov 18, 2017 06:45 AM 2 207 Nov 18, 2017 06:45 AM
Last Post: CrypticX
[Python] by mutybyteAug 1, 2017 02:51 AM 2 258 Aug 1, 2017 02:51 AM
Last Post: Consulting Detective