coding issue - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: coding issue (/thread-2003.html) |
coding issue - Lee - Feb-10-2017 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:
RE: coding issue - Ofnuts - Feb-10-2017 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])) Recommended: https://www.youtube.com/watch?v=_AEJHKGk9ns
RE: coding issue - Lee - Feb-13-2017 Hi Ofnuts Good answer and teaching web. Thank you. |