0

I know that the following breaks up a list and put it into two lists depending on whether an index is even or odd. But not sure how [n::2] for n in [1,0] works.

[[1,2,3,4,5][n::2] for n in [1, 0] ] [[2, 4], [1, 3, 5]]

Can you point me to post that explain and walk me through the logic behind it? Thank you.

ubrmax
  • 1
  • 1
  • Welcome to stack overflow, what language should this be? Python? – Catalyst Feb 23 '19 at 20:55
  • Assuming it is python - check out https://stackoverflow.com/questions/3453085/what-is-double-colon-in-python-when-subscripting-sequences – Catalyst Feb 23 '19 at 21:01

1 Answers1

0

The left part happens with each value of n. n indicates the starting position to take the 2nd element including the n'th one.

print([[1,2,3,4,5][n::2] for n in [1, 0] ] )

print([[1,2,3,4,5][1::2]]) # outputs [[2, 4]]
print([[1,2,3,4,5][0::2]]) # outputs [[1, 3, 5]]
print([[1,2,3,4,5][4::2]]) # outputs [[5]]
Catalyst
  • 3,143
  • 16
  • 20