Dec-13-2017, 01:05 PM
Your syntax is wrong; there are no commas in the [].
Slices are really convenient ways to create a sublist (or tuple or array) from an existing one.
The syntax is [start:end:step]. The step field is frequently omitted and defaults to 1. If you omit start and end, they default to... the start and end.
Slices are really convenient ways to create a sublist (or tuple or array) from an existing one.
The syntax is [start:end:step]. The step field is frequently omitted and defaults to 1. If you omit start and end, they default to... the start and end.
>>> l = [1,2,3,4] >>> l[:] # create a new list from the old one [1, 2, 3, 4]The slice creates a new list:
>>> x = l[:] >>> x # x has the same elements as l [1, 2, 3, 4] >>> x.append(5) # add a new one to x >>> l # l doesn't get the new element [1, 2, 3, 4] >>> x # but x does [1, 2, 3, 4, 5]When would you use slices? I use them when parsing formatted text if I know, for example that two fields are the first and last name:
>>> x = "Matthew Doe New York" >>> y = x.split(' ') >>> y[:2] ['Matthew', 'Doe']You can easily reverse a list with the step field:
>>> l [1, 2, 3, 4] >>> l[::-1] [4, 3, 2, 1]So that's a quick rundown of how to use slices. I wouldn't say that I use them a lot but they are an extremely useful tool to be familiar with.