Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inserting items in a list with python while looping

I’am trying to change the following code to get the following return :

"1 2 3 … 31 32 33 34 35 36 37 … 63 64 65"

def createFooter2(current_page, total_pages, boundaries, around) -> str:
    footer = []
    page = 1
    #Append lower boundaries
    while page <= boundaries:
        footer.append(page)
        page += 1
    #Append current page and arround
    page = current_page - around
    while page <= current_page + around:
        footer.append(page)
        page += 1
    #Append upper boundaries
    page = total_pages - boundaries + 1
    while page <= total_pages:
        footer.append(page)
        page += 1
    #Add Ellipsis if necessary
    for i in range(len(footer)):
        if i > 0 and footer[i] - footer[i - 1] > 1:
            footer.insert(i, "...")
    result = ' '.join(str(page) for page in result)
    print(result)
    return result

createFooter2(34, 65, 3, 3)

I want to insert an "…" between the pages if the next page is not directly next to it. However Iam having trouble inserting into the list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How should I change the code to make it work ?

>Solution :

As I commented, I first log all discontinuity indexes, then insert ‘…’ from higher to lower (since modifying an iterable you’re looping through will cause problems otherwise):

a = list(range(50))
a.remove(6)
a.remove(23)
a.remove(45)

indexes = []
for i in range(1,len(a)):
    if a[i] != a[i-1]+1:
        indexes.append(i)

for i in indexes[::-1]:
    a.insert(i,'...')

a
# [0, 1, 2, 3, 4, 5, '...', 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, '...', 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, '...', 46, 47, 48, 49]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading