1

I'm study Learnpythonthehardway, in ex40, I met this slice of code.

for sentence in snippet, phrase:
    result = sentence[:]

I'm not quite understanding sentence[:] here, especially the [:]

I've tried to figure it out by underlying test code:

sentence = 'sss errf : fe : eee'
f = 33
result = sentence[:f]
print result

but nothing happens, result is the same as the sentence

So, smart geeks, what does sentence[:] mean here?

Mario
  • 921
  • 2
  • 10
  • 22
  • 2
    As explained by @inclement, `[:]` is used for lists, but in this exercise `sentence` is a string so I don't see why he used `[:]`. – Gjekask Jul 31 '16 at 21:05

1 Answers1

3

This is a use of python's list slice syntax that simply means 'copy the whole list'.

You might often do something like some_list[:5] to get the first 5 elements, or some_list[5:] to get everything from the fifth element onwards (or sixth element onwards if you count the zeroth as the first, since python lists are zero-indexed). If you think like that, it's natural that the syntax means everything from the first element to the last one.

An important thing here is that this does produce a copy of the list, not a reference to the original list. That means it can be a useful way to clone a list, it doesn't just do nothing.

inclement
  • 29,124
  • 4
  • 48
  • 60
  • Another important note is that alhtough it produces a copy of the list, it may still contain references, not copies, of sublists. To avoid this, use `copy.deepcopy`. – rlms Dec 26 '13 at 15:18