Free preview

100 lessons

Python Done Right

Free preview

Python Done Right · 100 lessons

Learn Python from scratch - syntax through to OOP

No surprise gaps

Actually remember it

Skip what you know

One subscription. All learning paths included.

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

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

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