Sunday, 3 March 2024

Slicing in Python

 

Example 1: Slicing a List

# Slicing a list

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

# Get elements from index 2 to 5 (exclusive)

subset = numbers[2:5]

print(subset)  # Output: [2, 3, 4]

#clcoding.com

[2, 3, 4]

Example 2: Omitting Start and End Indices

# Omitting start and end indices

subset = numbers[:7]  # From the beginning to index 6

print(subset)  # Output: [0, 1, 2, 3, 4, 5, 6]

subset = numbers[3:]  # From index 3 to the end

print(subset)  # Output: [3, 4, 5, 6, 7, 8, 9]

#clcoding.com

[0, 1, 2, 3, 4, 5, 6]

[3, 4, 5, 6, 7, 8, 9]

Example 3: Using Negative Indices

# Using negative indices

subset = numbers[-4:-1]  

print(subset)  

#clcoding.com

[6, 7, 8]

Example 4: Slicing a String

# Slicing a string

text = "Hello, Python!"

# Get the substring "Python"

substring = text[7:13]

print(substring)  # Output: Python

#clcoding.com

Python

Example 5: Step in Slicing

# Step in slicing

even_numbers = numbers[2:10:2]  

print(even_numbers)  

#clcoding.com

[2, 4, 6, 8]

Example 6: Slicing with Stride

# Slicing with stride

reverse_numbers = numbers[::-1] 

print(reverse_numbers)  

#clcoding.com

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

Example 7: Slicing a Tuple

# Slicing a tuple

my_tuple = (1, 2, 3, 4, 5)

# Get a sub-tuple from index 1 to 3

subset_tuple = my_tuple[1:4]

print(subset_tuple)  # Output: (2, 3, 4)

#clcoding.com

(2, 3, 4)

Example 8: Modifying a List with Slicing

# Modifying a list with slicing

letters = ['a', 'b', 'c', 'd', 'e']

# Replace elements from index 1 to 3

letters[1:4] = ['x', 'y', 'z']

print(letters)  

#clcoding.com

['a', 'x', 'y', 'z', 'e']

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (363) Python Quiz (25) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses