Python Forum
How to generate the list I want?
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to generate the list I want?
#1
Hi :)

I want to generate a list of lists of the form:

[ [0, 4, 4, 4, 4]
  [4, 0, 4, 4, 4]
  [4, 4, 0, 4, 4]
  [4, 4, 4, 0, 4]
  [4, 4, 4, 4, 0] ]
Nothing I'm trying works, it seems python wants to simplify my life by changing all the lists indices instead of just the one i'm pointing at him. Examples:

Xs = [[4]*5]*5
for i, X in enumerate(Xs):
    Xs[i][i] = 0
print Xs

Xs, t = [], [4, 4, 4, 4, 4]
for i in range(5):
    Xs.append(t)
    Xs[i][i] = 0
print Xs

Xs, t = [], [4, 4, 4, 4, 4]
for i in range(5):
    temp = t
    temp[i] = 0
    Xs.append(temp)
print Xs
print t, "f you, i don't even touch t"
outputs:
Output:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] [0, 0, 0, 0, 0] f you, i don't even touch t
In reality, I need to make a slightly bigger list, and I could totally make it by hand, but seriously what is this behaviour? Not only it's totally unintuitive, but especially the last example is ridiculous, I just can't find how to generate that... Is my logic flawed there and I'm too blind to see?

Yes I'm a bit angry because I just lost one hour to understand why my monte-carlo optimization of non-convex stuff did send me errors it shouldn't. It's easy, I don't have the starting list of indices I should have.
Reply


Messages In This Thread
How to generate the list I want? - by Krookroo - Sep-07-2017, 03:28 AM
RE: How to generate the list I want? - by Larz60+ - Sep-07-2017, 11:54 AM
RE: How to generate the list I want? - by Krookroo - Sep-07-2017, 12:19 PM
RE: How to generate the list I want? - by Larz60+ - Sep-07-2017, 12:50 PM
RE: How to generate the list I want? - by Krookroo - Sep-07-2017, 01:40 PM
RE: How to generate the list I want? - by wavic - Sep-07-2017, 01:46 PM
RE: How to generate the list I want? - by Krookroo - Sep-07-2017, 02:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Generate a list sasitha96 5 2,516 Sep-20-2021, 07:03 PM
Last Post: sasitha96
  How to generate a log in a list style? wagnergt12 5 2,905 Apr-22-2020, 12:47 PM
Last Post: buran
  extract first and last 5 elements from given list and generate a new list. Raj_Kumar 1 2,442 Dec-07-2019, 05:03 PM
Last Post: ichabod801
  I created a function that generate a list but the list is empty in a new .py file mrhopeedu 2 2,431 Oct-12-2019, 08:02 PM
Last Post: mrhopeedu
  Generate list in class P13N 7 4,545 Dec-28-2018, 10:08 PM
Last Post: P13N
  Generate a list of numbers within a list of arbitrary numbers Takeshio 4 3,633 Nov-08-2018, 12:29 AM
Last Post: Takeshio

Forum Jump:

User Panel Messages

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