0

still trying to crack parts of code written by a colleague who took a new job. The following has me stumped.

sidd1_fractions = [ ([0.0] * (sidd1_size + 2*flanking_size))[:] for x in range(labels.max()+1) ]

Here, he is setting up a series of lists (or arrays) filled with zeros. Not shown is that in later steps he fills these up with data. So this is basically a placeholder for future data.

My question is that what is the purpose of [:]? It normally indicates to slice an entire list but I have seen very similar code which lacks the [:].

HIMANSHU PANDEY
  • 684
  • 1
  • 10
  • 22
  • It's a shortcut to make a *copy* of the original list instead of generating another reference to that list. – Mark Ransom Nov 26 '22 at 01:58
  • The question used as a duplicate is not really a duplicate, it addresses having the `[:]` on the left side of the assignment and not the right. – Mark Ransom Nov 26 '22 at 02:00
  • thanks Mark. still a bit confused by what you mean by the "original list". What would happen if you left out the [:] vs having it? – Emil Michelotti Nov 26 '22 at 02:09
  • @MarkRansom I think I've found an appropriate duplicate instead. – Karl Knechtel Nov 26 '22 at 09:56
  • 1
    Anyway, it doesn't have a real purpose in this particular code. The author of the code seems to intend to copy the `([0.0] * (sidd1_size + 2*flanking_size))` result in order to avoid having multiple lists sharing the same contents. However, that is not a concern here because `[0.0] * (sidd1_size + 2*flanking_size)` is a list containing multiple copies of the float object `0.0`, which **is immutable**. – Karl Knechtel Nov 26 '22 at 09:59
  • thanks Karl. Yes, I ended up running it alone with and without the [:] and the results were identical. you are correct it has not real purpose – Emil Michelotti Nov 27 '22 at 01:48

0 Answers0