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?
#7
a = [4, 4, 4, 4]
c = []
for i in range(4):
    b = [elem for elem in a]
    b[i] = 0
    c.append(b)
print c
Output:
[[0, 4, 4, 4], [4, 0, 4, 4], [4, 4, 0, 4], [4, 4, 4, 0]]
Pheeew I managed to find a way without a module.
Apparently, the list stays in memory as an element and the variables refering to the list are just pointers to it, and not a container containing a separate value we can work on without affecting the initial list.
Creating another list from the first one and modifying the second one makes it so we are not changing the original list and therefore stuff works.
It's "just" computationally inefficient.

Edit: Okay so I realize now that I could update the initial list with the X of "for x, X in enumerate(blah)" instead of pointing to the original list with all the indices like I was doing. I guess it's gonna clean up my code quite a bit.
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,413 Sep-20-2021, 07:03 PM
Last Post: sasitha96
  How to generate a log in a list style? wagnergt12 5 2,806 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,394 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,332 Oct-12-2019, 08:02 PM
Last Post: mrhopeedu
  Generate list in class P13N 7 4,383 Dec-28-2018, 10:08 PM
Last Post: P13N
  Generate a list of numbers within a list of arbitrary numbers Takeshio 4 3,520 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