Python array value allocation glitch
Solved, thanks to everyone for their help!
My array generation code was referencing the same array, so edits would apply to whole columns instead of specific points.
I'm making a few functions I can use in future programs in Python to do with arrays, such as defining them and displaying them. However, I came across a strange bug or glitch while trying to set values in order in an array from left to right. For some reason, when the program sets values on the last y value, (or actually on any value,) it sets that value for the whole column instead for just one, even though I only have 2 loops. Here's my code:
def gen(xLen, yLen, fill = 0):
mainArr = list()
secArr = list()
for i in range(xLen):
secArr.append(fill)
for i in range(yLen):
mainArr.append(secArr)
return mainArr
def sums(xLen, yLen):
newArr = gen(xLen, yLen)
a = 0
for y in range(yLen):
for x in range(xLen):
newArr[y][x] = a
print(str(x) + ", " + str(y) + " = " + str(a)) #For debugging, what the array SHOULD contain
a += 1
return newArr
(Just run this with print(sums(5, 5))
)
Instead of returning with [[0, 1, 2, 3, 4], ... [20, 21, 22, 23, 24]]
, it returns with a list full of [20, 21, 22, 23, 24]
and I really don't know why.
I don't want to append a new list to another list with values already in them, for example arr.append([0, 1, 2, 3, 4])
, because the array is already generated.
Why doesn't this work??? It's been bugging me for weeks!
python arrays list
add a comment |
Solved, thanks to everyone for their help!
My array generation code was referencing the same array, so edits would apply to whole columns instead of specific points.
I'm making a few functions I can use in future programs in Python to do with arrays, such as defining them and displaying them. However, I came across a strange bug or glitch while trying to set values in order in an array from left to right. For some reason, when the program sets values on the last y value, (or actually on any value,) it sets that value for the whole column instead for just one, even though I only have 2 loops. Here's my code:
def gen(xLen, yLen, fill = 0):
mainArr = list()
secArr = list()
for i in range(xLen):
secArr.append(fill)
for i in range(yLen):
mainArr.append(secArr)
return mainArr
def sums(xLen, yLen):
newArr = gen(xLen, yLen)
a = 0
for y in range(yLen):
for x in range(xLen):
newArr[y][x] = a
print(str(x) + ", " + str(y) + " = " + str(a)) #For debugging, what the array SHOULD contain
a += 1
return newArr
(Just run this with print(sums(5, 5))
)
Instead of returning with [[0, 1, 2, 3, 4], ... [20, 21, 22, 23, 24]]
, it returns with a list full of [20, 21, 22, 23, 24]
and I really don't know why.
I don't want to append a new list to another list with values already in them, for example arr.append([0, 1, 2, 3, 4])
, because the array is already generated.
Why doesn't this work??? It's been bugging me for weeks!
python arrays list
1
It's not clear to me what function you expect to return a list of lists, or if that's even what you're trying to get. Could you edit your question to focus more on clearly explaining your problem and what you're trying to achieve?
– code_dredd
Nov 23 '18 at 1:08
add a comment |
Solved, thanks to everyone for their help!
My array generation code was referencing the same array, so edits would apply to whole columns instead of specific points.
I'm making a few functions I can use in future programs in Python to do with arrays, such as defining them and displaying them. However, I came across a strange bug or glitch while trying to set values in order in an array from left to right. For some reason, when the program sets values on the last y value, (or actually on any value,) it sets that value for the whole column instead for just one, even though I only have 2 loops. Here's my code:
def gen(xLen, yLen, fill = 0):
mainArr = list()
secArr = list()
for i in range(xLen):
secArr.append(fill)
for i in range(yLen):
mainArr.append(secArr)
return mainArr
def sums(xLen, yLen):
newArr = gen(xLen, yLen)
a = 0
for y in range(yLen):
for x in range(xLen):
newArr[y][x] = a
print(str(x) + ", " + str(y) + " = " + str(a)) #For debugging, what the array SHOULD contain
a += 1
return newArr
(Just run this with print(sums(5, 5))
)
Instead of returning with [[0, 1, 2, 3, 4], ... [20, 21, 22, 23, 24]]
, it returns with a list full of [20, 21, 22, 23, 24]
and I really don't know why.
I don't want to append a new list to another list with values already in them, for example arr.append([0, 1, 2, 3, 4])
, because the array is already generated.
Why doesn't this work??? It's been bugging me for weeks!
python arrays list
Solved, thanks to everyone for their help!
My array generation code was referencing the same array, so edits would apply to whole columns instead of specific points.
I'm making a few functions I can use in future programs in Python to do with arrays, such as defining them and displaying them. However, I came across a strange bug or glitch while trying to set values in order in an array from left to right. For some reason, when the program sets values on the last y value, (or actually on any value,) it sets that value for the whole column instead for just one, even though I only have 2 loops. Here's my code:
def gen(xLen, yLen, fill = 0):
mainArr = list()
secArr = list()
for i in range(xLen):
secArr.append(fill)
for i in range(yLen):
mainArr.append(secArr)
return mainArr
def sums(xLen, yLen):
newArr = gen(xLen, yLen)
a = 0
for y in range(yLen):
for x in range(xLen):
newArr[y][x] = a
print(str(x) + ", " + str(y) + " = " + str(a)) #For debugging, what the array SHOULD contain
a += 1
return newArr
(Just run this with print(sums(5, 5))
)
Instead of returning with [[0, 1, 2, 3, 4], ... [20, 21, 22, 23, 24]]
, it returns with a list full of [20, 21, 22, 23, 24]
and I really don't know why.
I don't want to append a new list to another list with values already in them, for example arr.append([0, 1, 2, 3, 4])
, because the array is already generated.
Why doesn't this work??? It's been bugging me for weeks!
python arrays list
python arrays list
edited Nov 23 '18 at 2:04
asked Nov 23 '18 at 0:58
64_Tesseract
63
63
1
It's not clear to me what function you expect to return a list of lists, or if that's even what you're trying to get. Could you edit your question to focus more on clearly explaining your problem and what you're trying to achieve?
– code_dredd
Nov 23 '18 at 1:08
add a comment |
1
It's not clear to me what function you expect to return a list of lists, or if that's even what you're trying to get. Could you edit your question to focus more on clearly explaining your problem and what you're trying to achieve?
– code_dredd
Nov 23 '18 at 1:08
1
1
It's not clear to me what function you expect to return a list of lists, or if that's even what you're trying to get. Could you edit your question to focus more on clearly explaining your problem and what you're trying to achieve?
– code_dredd
Nov 23 '18 at 1:08
It's not clear to me what function you expect to return a list of lists, or if that's even what you're trying to get. Could you edit your question to focus more on clearly explaining your problem and what you're trying to achieve?
– code_dredd
Nov 23 '18 at 1:08
add a comment |
3 Answers
3
active
oldest
votes
secArr
is a reference to a list.
So in gen
you are actually placing n
times the same reference to secArr
in mainArr
.
Add a print(newArr)
in the for to verify this.
You can run newArr[0][1] = 1
to see how all the inner lists are affected.
You can solve this by creating a copy of secArr
before appending it to mainArr
in gen
, like this:
mainArr.append(secArr[:])
More on the topic here or here.
This answer is good, but I would actually suggest doingmainArr.append(secArr.copy())
- I feel that the explicit copy makes it more obvious what's going on.
– AetherUnbound
Nov 23 '18 at 1:49
add a comment |
While Julian Peller's answer answers your specific question, I would propose a way cleaner and more pythonic way to do your tasks:
def gen2(xLen, yLen, fill=0):
return [[fill for x in range(xLen)] for y in range(yLen)]
def sums2(xLen, yLen):
return [[y*yLen+x for x in range(xLen)] for y in range(yLen)]
These functions are using list comprehensions which are more readable and avoid making errors like yours for example
add a comment |
You are seeing the same effects as the person who asked this question. I hope my answer, and the other linked answers can help you understand why this is happening, and how to fix it.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439537%2fpython-array-value-allocation-glitch%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
secArr
is a reference to a list.
So in gen
you are actually placing n
times the same reference to secArr
in mainArr
.
Add a print(newArr)
in the for to verify this.
You can run newArr[0][1] = 1
to see how all the inner lists are affected.
You can solve this by creating a copy of secArr
before appending it to mainArr
in gen
, like this:
mainArr.append(secArr[:])
More on the topic here or here.
This answer is good, but I would actually suggest doingmainArr.append(secArr.copy())
- I feel that the explicit copy makes it more obvious what's going on.
– AetherUnbound
Nov 23 '18 at 1:49
add a comment |
secArr
is a reference to a list.
So in gen
you are actually placing n
times the same reference to secArr
in mainArr
.
Add a print(newArr)
in the for to verify this.
You can run newArr[0][1] = 1
to see how all the inner lists are affected.
You can solve this by creating a copy of secArr
before appending it to mainArr
in gen
, like this:
mainArr.append(secArr[:])
More on the topic here or here.
This answer is good, but I would actually suggest doingmainArr.append(secArr.copy())
- I feel that the explicit copy makes it more obvious what's going on.
– AetherUnbound
Nov 23 '18 at 1:49
add a comment |
secArr
is a reference to a list.
So in gen
you are actually placing n
times the same reference to secArr
in mainArr
.
Add a print(newArr)
in the for to verify this.
You can run newArr[0][1] = 1
to see how all the inner lists are affected.
You can solve this by creating a copy of secArr
before appending it to mainArr
in gen
, like this:
mainArr.append(secArr[:])
More on the topic here or here.
secArr
is a reference to a list.
So in gen
you are actually placing n
times the same reference to secArr
in mainArr
.
Add a print(newArr)
in the for to verify this.
You can run newArr[0][1] = 1
to see how all the inner lists are affected.
You can solve this by creating a copy of secArr
before appending it to mainArr
in gen
, like this:
mainArr.append(secArr[:])
More on the topic here or here.
edited Nov 23 '18 at 1:13
answered Nov 23 '18 at 1:07
Julian Peller
864511
864511
This answer is good, but I would actually suggest doingmainArr.append(secArr.copy())
- I feel that the explicit copy makes it more obvious what's going on.
– AetherUnbound
Nov 23 '18 at 1:49
add a comment |
This answer is good, but I would actually suggest doingmainArr.append(secArr.copy())
- I feel that the explicit copy makes it more obvious what's going on.
– AetherUnbound
Nov 23 '18 at 1:49
This answer is good, but I would actually suggest doing
mainArr.append(secArr.copy())
- I feel that the explicit copy makes it more obvious what's going on.– AetherUnbound
Nov 23 '18 at 1:49
This answer is good, but I would actually suggest doing
mainArr.append(secArr.copy())
- I feel that the explicit copy makes it more obvious what's going on.– AetherUnbound
Nov 23 '18 at 1:49
add a comment |
While Julian Peller's answer answers your specific question, I would propose a way cleaner and more pythonic way to do your tasks:
def gen2(xLen, yLen, fill=0):
return [[fill for x in range(xLen)] for y in range(yLen)]
def sums2(xLen, yLen):
return [[y*yLen+x for x in range(xLen)] for y in range(yLen)]
These functions are using list comprehensions which are more readable and avoid making errors like yours for example
add a comment |
While Julian Peller's answer answers your specific question, I would propose a way cleaner and more pythonic way to do your tasks:
def gen2(xLen, yLen, fill=0):
return [[fill for x in range(xLen)] for y in range(yLen)]
def sums2(xLen, yLen):
return [[y*yLen+x for x in range(xLen)] for y in range(yLen)]
These functions are using list comprehensions which are more readable and avoid making errors like yours for example
add a comment |
While Julian Peller's answer answers your specific question, I would propose a way cleaner and more pythonic way to do your tasks:
def gen2(xLen, yLen, fill=0):
return [[fill for x in range(xLen)] for y in range(yLen)]
def sums2(xLen, yLen):
return [[y*yLen+x for x in range(xLen)] for y in range(yLen)]
These functions are using list comprehensions which are more readable and avoid making errors like yours for example
While Julian Peller's answer answers your specific question, I would propose a way cleaner and more pythonic way to do your tasks:
def gen2(xLen, yLen, fill=0):
return [[fill for x in range(xLen)] for y in range(yLen)]
def sums2(xLen, yLen):
return [[y*yLen+x for x in range(xLen)] for y in range(yLen)]
These functions are using list comprehensions which are more readable and avoid making errors like yours for example
answered Nov 23 '18 at 1:14
user8408080
1,121139
1,121139
add a comment |
add a comment |
You are seeing the same effects as the person who asked this question. I hope my answer, and the other linked answers can help you understand why this is happening, and how to fix it.
add a comment |
You are seeing the same effects as the person who asked this question. I hope my answer, and the other linked answers can help you understand why this is happening, and how to fix it.
add a comment |
You are seeing the same effects as the person who asked this question. I hope my answer, and the other linked answers can help you understand why this is happening, and how to fix it.
You are seeing the same effects as the person who asked this question. I hope my answer, and the other linked answers can help you understand why this is happening, and how to fix it.
answered Nov 23 '18 at 1:39
David Culbreth
755513
755513
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439537%2fpython-array-value-allocation-glitch%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
It's not clear to me what function you expect to return a list of lists, or if that's even what you're trying to get. Could you edit your question to focus more on clearly explaining your problem and what you're trying to achieve?
– code_dredd
Nov 23 '18 at 1:08