# Extract a sublist containing the last three items of a list my_list = [1, 2, 3, 4, 5] last_three = my_list[-3:] # This would return [3, 4, 5] # Extract a sublist containing every other item of a list, starting with the second item my_list = [1, 2, 3, 4, 5] every_other = my_list[1::2] # This would return [2, 4] # Extract a sublist containing the first three items of a string my_string = "Hello, world!" first_three = my_string[:3] # This would return "Hel"
In Python, the slice notation is a way of accessing a part of a string, list, or tuple. The syntax for the slice notation is start:end:step, where start is the starting index, end is the ending index, and step is the number of items to skip between items in the sliced sequence. For example, if you have a list my_list = [1, 2, 3, 4, 5] and you want to extract a sublist that contains the second and third items, you could use the following slice notation: my_list[1:3], which would return the list [2, 3].
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.