Preview

A lesson from Python Done Right

£29/month

£29/month£29/month or £249/year · 30-day money-back guarantee

Get full access

Our content is best on a larger screen

Slicing sequences

Introduction to sequence slicing

Explanation

Slicing extracts a portion of a sequence (list, tuple, or string) without altering the original.

Syntax

sequence[start:stop]
  • start - index where the slice begins (inclusive)
  • stop - index where the slice ends (exclusive)

Either can be omitted: sequence[:stop] starts from the beginning, sequence[start:] goes to the end.

Why is start inclusive but stop exclusive?

Details

Copying a list with [:]

A full slice [:] creates a copy of a list with a different memory address. For immutable types like tuples and strings, [:] returns the same object since copies aren't needed.

Info

Key points:

  • Slicing always returns a new sequence, leaving the original unchanged
  • If start == stop, an empty sequence is returned
  • Slicing always returns a sequence, even for a single element

Practice questions

4 questions

What will my_sequence[2:5] return when slicing a sequence in Python?

Select the correct answer:

+ 3 more questions · unlocked with a subscription

Slicing a list and tuple

Example

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(numbers[0:5])  # Output: [0, 1, 2, 3, 4]
print(numbers[6:])   # Output: [6, 7, 8, 9]
print(numbers[:3])   # Output: [0, 1, 2]

Tuples work the same way:

nums = (0, 1, 2, 3, 4, 5)
print(nums[2:5])  # Output: (2, 3, 4)

Copying a list with [:]

list_1 = [1, 2, 3]
list_2 = list_1[:]       # creates a copy
list_1.append(99)
print(list_2)            # Output: [1, 2, 3] (unaffected)

list_2 wasn't impacted because it's a separate object.

Practice questions

5 questions

In the Python Console there's a list variable defined called numbers.

Slice the first 8 elements of the list and assign the sublist to a variable named answer.

Once done, press submit.

+ 4 more questions · unlocked with a subscription

Slicing a string

Example

Strings support the same slicing syntax:

greeting = "Hello, World!"

print(greeting[0:5])   # Output: Hello
print(greeting[7:])    # Output: World!
print(greeting[:5])    # Output: Hello
phrase = "Python Programming"

print(phrase[:6])   # Output: Python
print(phrase[7:])   # Output: Programming

Practice questions

4 questions

In the Python Console, there's a string variable defined called quote.

Slice out the first 31 characters of the variable and assign the resulting substring to a variable named answer.

Once done, press submit.

+ 3 more questions · unlocked with a subscription

Memory is built by recalling, not by reading.

Every time you pull an answer from memory, the memory gets stronger. Reading doesn't do that. Nodeledge asks you questions on every step of every lesson, then asks again after days, weeks and months.

Get full access

£29/month or £249/year · 30-day money-back guarantee

See the learning path