Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
coding issue
#1
I wirte a simple as following.
Could someone can tell me why the answer is different Buf1 and Buf2 ??
Thank for you help.

def fList_Test(pBuf, pX):
    pBuf.clear()
    _bufX = []
    if pX == 0:
        _bufX = ['a1', 'a2']
    elif pX == 1:
        _bufX = ['b1', 'b2']
    else:
        _bufX = ['c1', 'c2']
    pBuf.append(_bufX)

Buf1 = []
Buf2 = []
Buf_T = []
for x in range(3):
    _bufX = []
    fList_Test(Buf_T, x)
    Buf1.append(Buf_T)
    fList_Test(_bufX, x)
    Buf2.append(_bufX)

print (Buf1)
print (Buf2)
output:
Output:
[[['c1', 'c2']], [['c1', 'c2']], [['c1', 'c2']]] [[['a1', 'a2']], [['b1', 'b2']], [['c1', 'c2']]]
Reply
#2
Because Buf1 contains three identical references to the same list, since Buf_T is only created once, while you get a new _bufX on every iteration on x. Try this at the end of your code:
for x in range(3):
    print ('Buf1[0] is Buf1[%d]: %s' % (x, Buf1[0] is Buf1[x]))
for x in range(3):
    print ('Buf2[0] is Buf2[%d]: %s' % (x, Buf2[0] is Buf2[x]))
Output:
Buf1[0] is Buf1[0]: True Buf1[0] is Buf1[1]: True Buf1[0] is Buf1[2]: True Buf2[0] is Buf2[0]: True Buf2[0] is Buf2[1]: False Buf2[0] is Buf2[2]: False
Recommended: https://www.youtube.com/watch?v=_AEJHKGk9ns
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#3
Hi Ofnuts
Good answer and teaching web.
Thank you.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Very basic coding issue aary 4 2,451 Jun-03-2020, 11:59 AM
Last Post: buran
  Very basic coding issue mstichler 3 2,588 Jun-03-2020, 04:35 AM
Last Post: mstichler
  Python Coding Issue! ankitdixit 3 89,271 Sep-25-2019, 06:31 AM
Last Post: rohanjoshi0894
  Coding issue 1557676 2 29,999 Aug-02-2019, 08:54 PM
Last Post: cvsae
  New member with simple coding issue shaikh 0 2,986 Apr-24-2017, 05:28 PM
Last Post: shaikh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020