简体   繁体   中英

How to return a list with the last item of the list repeated?

I'm confused as to how I would complete the second half of this question.

Write a that takes a list item which contains integers and returns the provided list if the number of items in the list is even, otherwise, it returns the list but with its last item repeated (in order to make the number of items in the list even).

This is what I have so far.

def balance_list(items):
    if len(items) % 2 == 0:
        return items
    else:
        return items.append

Does this solve your question?

def balance_list(items):
    if len(items) % 2 == 1:
        items.append(items[-1])
    return items

print(balance_list([1, 2, 3, 4, 5]))

Happy Coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM