# Retrieve a single item from a list with a given index
elements = ["H", "He", "Li", "B", "C", "N", "O", "F", "Ne"]
print(elements[2]) # Prints 'Li'

# Use a colon inside the index brackets to get a "slice" of the list, returned
# as a list.
element_slice = elements[1:5] # from index 0 up to (not including) index 5
print(element_slice) # Prints ['He', 'Li', 'B', 'C']

# If a number is not specified at the beginning of the range, it's assumed to
# be 0 (or the beginning of the list).
element_slice = elements[:3] # get the first three elements
print(element_slice) # Prints ['H', 'He', 'Li']

# If a number is not specified at the end of the range, the slice will extend
# to the end of the list.
element_slice = elements[6:] # from index 6 to the end of the list
print(element_slice) # Prints ['O', 'F', 'Ne']

# Without either a first number or a second number, the slice extends from
# the beginning of the list to the end of the list, effectively making a copy.
element_slice = elements[:]
print(element_slice) # Prints ['H', 'He', 'Li', 'B', 'C', 'N', 'O', 'F', 'Ne']

# Negative indexes can be used for either element of the range.
element_slice = elements[-2:] # last two elements of the list
print(element_slice) # Prints ['F', 'Ne']

element_slice = elements[-5:-2] # 5 elements from end to 2 elements from end
print(element_slice) # Prints ['C', 'N', 'O']

# You can use slice syntax with strings as well:
message = "Now is the winter of our discontent"
print(message[:10]) # Prints 'Now is the'
print(message[11:20]) # Prints 'winter of'
print(message[-7:]) # Prints 'content'

Description Python's index bracket syntax allows you to easily write expressions that evaluate to a section, or "slice," of a list. The syntax for getting a slice of a list looks very similar to the syntax for getting a single item, except instead of putting a single number inside the square brackets, you put two numbers, separated by a colon, indicating where the slice should start and end.

For example, the expression x[n:m] evaluates to a list that contains items from index n up to (but not including) index m from a list x. If n is omitted, it's assumed to be 0, and the slice will begin at the beginning of the list. If m is omitted, the slice will end at the end of the list.

When slice indexes are negative, they follow the same rules for negative indexes in general (see index brackets for more information).

Slice syntax works with strings as well, and is a convenient way to extract substrings by numerical index.

sequencelist: string or other sequence
beginint: index at which to begin the slice
endint: integer index at which to end the slice
Updated on Tue Jul 11 06:52:24 2017.
Creative Commons License