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

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (115) C (77) C# (12) C++ (82) Course (62) Coursera (178) coursewra (1) Cybersecurity (22) data management (11) Data Science (91) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (747) Python Coding Challenge (202) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

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