How do I slice lists and strings in Python?

In Python, slicing is a powerful technique that allows you to extract parts of lists and strings. By specifying a range of indices, you can obtain a new list or string that is derived from the original.

Slicing Lists

To slice a list, you can use the syntax list[start:end:step]. Here’s a simple example:

# Example of list slicing in Python my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sliced_list = my_list[2:8:2] # Output will be [3, 5, 7] print(sliced_list)

Slicing Strings

Similarly, you can slice strings using the same syntax. Here’s how you can extract a substring:

# Example of string slicing in Python my_string = "Hello, World!" sliced_string = my_string[7:12] # Output will be 'World' print(sliced_string)

Python list slicing string slicing programming tutorial