0% found this document useful (0 votes)
14 views8 pages

Python Slicing Explained with Examples

Slicing python document

Uploaded by

onemintreview
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Python Slicing Explained with Examples

Slicing python document

Uploaded by

onemintreview
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Slicing in Python

Understanding Python Slicing with


Examples
Introduction to Slicing
• Slicing in Python allows extracting specific
portions of sequences such as lists, tuples, and
strings.
Basic Syntax of Slicing
• Syntax: sequence[start:stop:step]
• - start: Index where slicing begins
• - stop: Index where slicing stops (exclusive)
• - step: The step size (optional)
Slicing Lists, Strings, and Tuples
• Examples:
• list1 = [1, 2, 3, 4, 5]
• print(list1[1:4]) # Output: [2, 3, 4]

• string = 'Python'
• print(string[:3]) # Output: 'Pyt'
Step Parameter in Slicing
• The step defines how many elements to skip:
• list1 = [0, 1, 2, 3, 4, 5]
• print(list1[::2]) # Output: [0, 2, 4]
Negative Indexing in Slicing
• Negative values count from the end:
• string = 'Python'
• print(string[-4:-1]) # Output: 'tho'
Advanced Slicing Techniques
• Reversing a list:
• list1 = [1, 2, 3, 4, 5]
• print(list1[::-1]) # Output: [5, 4, 3, 2, 1]
Conclusion & Practice Questions
• Practice:
• 1. Extract the first three elements from a list.
• 2. Reverse a string using slicing.
• 3. Extract alternate elements from a tuple.

You might also like