Implementing a Python Pagination Function
Many applications, especially those dealing with large datasets, require breaking down information into manageable pages. This challenge involves creating a Python function that generates paginated data, returning a specific subset of items based on the requested page number and the number of items per page.
Problem Description
Your task is to implement a Python function, paginate_list, that takes a list of items, a page number, and the number of items per page as input. The function should return a new list containing only the items belonging to the requested page.
Key Requirements:
- The function should handle valid page numbers and items per page.
- It should return an empty list if the requested page is out of bounds (e.g., requesting a page beyond the last available page).
- The function should gracefully handle cases where the total number of items is not perfectly divisible by the items per page.
Expected Behavior:
- Given a list of
items,page_number, anditems_per_page, return a slice ofitemsrepresenting the specified page. - Page numbers are 1-indexed (i.e., the first page is 1).
- The
page_numberanditems_per_pagewill be positive integers.
Edge Cases to Consider:
- An empty input list.
- Requesting a page number that is too high.
- Requesting a page number of 1 when the list is empty or has few items.
items_per_pageis larger than the total number of items.
Examples
Example 1:
Input:
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
page_number = 2
items_per_page = 3
Output:
[4, 5, 6]
Explanation: The first page contains items 1, 2, 3. The second page starts after these, so it contains the next 3 items: 4, 5, and 6.
Example 2:
Input:
items = ['apple', 'banana', 'cherry', 'date', 'elderberry']
page_number = 3
items_per_page = 2
Output:
['elderberry']
Explanation:
Page 1: ['apple', 'banana']
Page 2: ['cherry', 'date']
Page 3: ['elderberry'] (This is the last item, and fewer than items_per_page)
Example 3:
Input:
items = [100, 200, 300]
page_number = 5
items_per_page = 5
Output:
[]
Explanation: The total number of items is 3. Requesting page 5, even with items_per_page of 5, is beyond the available data, so an empty list is returned.
Example 4:
Input:
items = []
page_number = 1
items_per_page = 10
Output:
[]
Explanation: An empty input list always results in an empty output, regardless of the page number or items per page.
Constraints
- The input
itemswill be a Python list. page_numberwill be a positive integer (>= 1).items_per_pagewill be a positive integer (>= 1).- The total number of items in the
itemslist will not exceed 1,000,000. - The
page_numberanditems_per_pagewill not exceed 10,000.
Notes
Consider how to calculate the starting and ending indices for slicing the list based on the page_number and items_per_page. Remember that Python list slicing is [start:end], where end is exclusive. Pay close attention to 1-based indexing for page_number versus 0-based indexing for Python lists.