0% found this document useful (0 votes)
13 views2 pages

Explain Slicing For Beginners

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

Explain Slicing For Beginners

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Slicing in Python: A Beginner's Guide

Slicing is a powerful technique in Python that allows you to extract specific portions of
sequences like strings, lists, and tuples. It's a way to create new sequences based on existing
ones.

Basic Syntax
The general syntax for slicing is:

Python

sequence[start:stop:step]

● sequence: The sequence you want to slice (e.g., string, list, tuple).
● start: The index of the first element to include (default is 0).
● stop: The index of the first element to exclude (default is the length of the sequence).
● step: The interval between elements (default is 1).

Examples
1. Extracting a Substring:

Python

string = "Hello, World!"


substring = string[7:12] # Extracts "World"
print(substring) # Output: World

2. Reversing a String:

Python

reversed_string = string[::-1] # Reverses the string


print(reversed_string) # Output: !dlroW ,olleH
3. Extracting Every Other Element:

Python

numbers = [1, 2, 3, 4, 5]
every_other = numbers[::2] # Extracts elements at indices 0, 2, and 4
print(every_other) # Output: [1, 3, 5]

4. Creating a Copy of a Sequence:

Python

original_list = [10, 20, 30]


copied_list = original_list[:] # Creates a copy of the list
print(copied_list) # Output: [10, 20, 30]

Key Points
● The start and stop indices are optional. If omitted, they default to the beginning and end of
the sequence, respectively.
● The step can be positive, negative, or zero. A negative step reverses the order of the
extracted elements.
● Slicing creates a new sequence, leaving the original sequence unchanged.

By understanding slicing, you can efficiently manipulate sequences in your Python programs.

You might also like