Home > Back-end >  List interval with offset
List interval with offset

Time:11-16

On a website, I have a pagination system. For each page, want to display a sublist of a list of items (15 items per page) coming from MongoEngine. The items are ordered by date of creation and I want to extract the last items created first.

My current approach is to extract 15 items from the current list, without reversing it for efficiency and using negative values.

I found a way to load the 14 first items with list slicing, but the last one is always missing. I have to add it manually by extending the list with the missing item.

Any solution to do it in a pythonic way and in 1 line ?

# If we want to load page 2
page_nb = 2

# Select 15 items
items_per_page = 15

# The offset if defined based on the page number I want to load
offset = (page_nb - 1) * items_per_page
  
# Simple list of items as an example
# values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
values = list(range(50))

# Does not load the last item [-offset -1] 
# selected_values = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
# As you can see 34 is missing
# Removing the -1 solves the issue for page_nb >= 2, but leads to an error for page_nb=1
selected_values = values[-offset - items_per_page:-offset -1]

# Here it is added correctly, but I'd like to remove this unnecessary step
# selected_values = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]
selected_values  = [values[-offset -1]]

CodePudding user response:

The ending index of a slice in Python does not include the value at the ending index itself, so you should not add -1 to the offset as the ending index of the slice as noted in your comment.

However, to deal with the first page, where offset is 0 and non-negative, you can make it a special case to fall back to None, which denotes to the last item when used as an ending index of a slice. Since 0 is falsey, you can conveniently use the or operation to default to None.

Change:

selected_values = values[-offset - items_per_page:-offset -1]

to:

selected_values = values[-offset - items_per_page:-offset or None]

CodePudding user response:

It may be cleaner without negative indices:

start = len(values) - (page_nb) * items_per_page
end = len(values) - (page_nb - 1) * items_per_page
start = max(0, start)

selected_values = values[start : end]
  • Related