Python Forum
Slicing syntax question
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Slicing syntax question
#2
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.

>>> 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.
Reply


Messages In This Thread
Slicing syntax question - by Oliver - Dec-13-2017, 12:35 PM
RE: Slicing syntax question - by mpd - Dec-13-2017, 01:05 PM
RE: Slicing syntax question - by wavic - Dec-13-2017, 01:20 PM
RE: Slicing syntax question - by Oliver - Dec-13-2017, 02:03 PM
RE: Slicing syntax question - by hshivaraj - Dec-13-2017, 02:24 PM
RE: Slicing syntax question - by DeaD_EyE - Dec-13-2017, 03:58 PM
RE: Slicing syntax question - by metulburr - Dec-13-2017, 04:14 PM
RE: Slicing syntax question - by Oliver - Dec-13-2017, 08:24 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020