0

I am working on a problem which is about unpacking a multi-nested list and want to understand why list slicing for this list doesn't look as expected.

Typically,  both L[0] and  L[:1] are the same because they both return the first element of the list.

However, if you look at the code block below, when I tested out L[0] == L[:1]  the result is FALSE. The difference is that L[:1] would have another outer bracket.  Can someone please explain the difference to me? 

L = [['a', ['cat'], 2],[[[3]], 'dog'], 4, 5]
print(L[0])
print(L[:1])
L[0] == L[:1]

this is the output of the code above:

['a', ['cat'], 2]

[['a', ['cat'], 2]]

False

  • 1
    They are not the same. One gets you _one element_ - the other a _sliced list_ containing the data of the slice - the fact that you slice out just one data element still means you get a list back - not whatever element is in it – Patrick Artner Jan 14 '22 at 13:39
  • "Typically, both L[0] and L[:1] are the same because they both return the first element of the list." No, they are **never the same**. `L[0]` returns the frist element of the list, `L[:1]` returns a list of length <= 1, so either `[L[0]` or `[]` – juanpa.arrivillaga Jan 14 '22 at 13:42

1 Answers1

-1

L[0] - one element of list L.

L[:1] - sublist of list L.

Psytho
  • 3,313
  • 2
  • 19
  • 27