Home > other >  Why does my list slice not return last 6 values in my problem
Why does my list slice not return last 6 values in my problem

Time:09-28

I am trying to return the last 6 values of a list but it doesn't work right. I want it to return [1, 2, 2, 3, 5, 6] but it returns [0, 0, 2, 5, 6] and I can't see why any help is appreciated.

nums1 = [1,2,3,0,0,0]
nums2 = [2,5,6]

ans = nums1   nums2
print(sorted(ans[-6:]))

CodePudding user response:

You need to sort before you slice:

print(sorted(ans)[-6:])

CodePudding user response:

You are selecting the last 6 element and then sorting, it'll be done otherway around.

print(sorted(ans)[-6:])
  • Related