PythonLists and tuples
List slicing [start:stop:step]
Getting, replacing, and deleting fragments of a list by index.
- Returns
- A new list (when reading).
- Changes the original
- No
Example
#Python
modules = ["Intro", "HTML", "CSS", "Flexbox", "Grid", "Project"]
print(modules[1:4])
print(modules[-2:])
print(modules[::2])
modules[2:5] = ["CSS and layouts"]
print(modules)Resultsaved result, you can check it
['HTML', 'CSS', 'Flexbox']
['Grid', 'Project']
['Intro', 'CSS', 'Grid']
['Intro', 'HTML', 'CSS and layouts', 'Project']
Definition and usage
#The slice list[start:stop] returns a new list with the items from index start to stop, without the item at stop. Negative indexes count from the end, and omitted bounds mean the start or the end of the list.
Slices also work on the left side of an assignment: my_list[1:3] = ["x"] replaces two items with one, and del my_list[:2] removes the first two.
The step is the third value: my_list[::2] takes every second item, and my_list[::-1] returns a reversed copy. The slice my_list[:] is a quick way to make a shallow copy.
Syntax
#Syntax
list[start:stop:step]More examples
#Python
items = list(range(1, 11))
page, per_page = 2, 4
print(items[(page - 1) * per_page : page * per_page])Resultsaved result, you can check it
[5, 6, 7, 8]
Good practices
#- Slices do not raise an error for out-of-range indexes, they return a shorter list.
- Pagination:
items[(page - 1) * size : page * size].
Related entries
#Spotted a mistake or missing an example? Write to us.