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

Python Basic List Slicing

The document provides an overview of basic slicing techniques in Python, including extracting elements from lists using specific indices, steps, and negative indexing. It also covers examples with nested lists for slicing sublists and extracting specific elements. Overall, it emphasizes the efficiency and power of slicing in list manipulation.

Uploaded by

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

Python Basic List Slicing

The document provides an overview of basic slicing techniques in Python, including extracting elements from lists using specific indices, steps, and negative indexing. It also covers examples with nested lists for slicing sublists and extracting specific elements. Overall, it emphasizes the efficiency and power of slicing in list manipulation.

Uploaded by

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

Basic Slicing

1. Extract elements from index 1 to 4 (exclusive):

numbers = [10, 20, 30, 40, 50, 60]


sliced = numbers[1:4] # [20, 30, 40]
print(sliced)

2. Extract from the start to a specific index:

numbers = [10, 20, 30, 40, 50, 60]


sliced = numbers[:3] # [10, 20, 30]
print(sliced)

3. Extract from a specific index to the end:

numbers = [10, 20, 30, 40, 50, 60]


sliced = numbers[3:] # [40, 50, 60]
print(sliced)

Using Step

1. Every second element:

numbers = [10, 20, 30, 40, 50, 60]


sliced = numbers[::2] # [10, 30, 50]
print(sliced)

2. Reverse the list:

numbers = [10, 20, 30, 40, 50, 60]


sliced = numbers[::-1] # [60, 50, 40, 30, 20, 10]
print(sliced)

3. Extract every third element:

numbers = [10, 20, 30, 40, 50, 60, 70, 80]


sliced = numbers[::3] # [10, 40, 70]
print(sliced)

Negative Indexing

1. Extract last 3 elements:

numbers = [10, 20, 30, 40, 50, 60]


sliced = numbers[-3:] # [40, 50, 60]
print(sliced)

2. Skip elements in reverse order:

numbers = [10, 20, 30, 40, 50, 60]


sliced = numbers[-1:-5:-2] # [60, 40]
print(sliced)
Examples with Nested Lists

1. Slice a sublist within nested lists:

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


sliced = nested[1:3] # [[4, 5, 6], [7, 8, 9]]
print(sliced)

2. Extract specific elements from sublists:

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


sliced = [row[1:] for row in nested] # [[2, 3], [5, 6], [8, 9]]
print(sliced)

Slicing is a powerful and efficient way to work with lists in Python.

You might also like