0

I am using python, I have a nested list like this

sequences_list = [[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]

I want to get a sort of sequences like this

sequences_list = [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5]]

this is my code

k = 1
j = 0
while (k <= len(sequences_list)):
    del sequences_list[j][k:]
    k = k+1
    j = j+1
print(sequences_list)

the result i get is

[[0], [0], [0], [0], [0], [0]]
Hichem Neggaz
  • 15
  • 1
  • 6
  • 1
    Are you sure? I'm getting your expected result when I run your code. – Mehdi Mostafavi Jun 21 '21 at 18:30
  • 2
    `sequences_list = [ i[:k] for k,i in enumerate(sequences_list,1)]`? – Patrick Artner Jun 21 '21 at 18:31
  • 1
    The problem is not visible in what you posted, but I'm quite sure it is created at the moment you *define* the original `sequences_list`. You probably just copied the same sublist. – trincot Jun 21 '21 at 18:31
  • Yep - you probably did something like `sequences_list = [[1,2,3,4,5]] * 5` wich creates 5 references to the same list so you modify the same data behind all these references to the same data – Patrick Artner Jun 21 '21 at 18:32
  • `[sequences_list[i][:i+1] for i in range(len(sequences_list))]` – badhusha muhammed Jun 21 '21 at 18:35
  • You are handling the same reference. Use `sequence_list = [ [1,2,3,4,5] for _ in range(5)]` to get different lists inside sequence_list - then your code works – Patrick Artner Jun 21 '21 at 18:38

1 Answers1

-1

Try this one

    sequences_list = [[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]

    print([element[0:po+1] for po,element in enumerate(sequences_list)]) 
Bahae El Hmimdi
  • 364
  • 1
  • 5