2

Suppose list1 is [a, y, k, x, d, l]

How do I make a new list containing the first two and last two alphabetically (a, d, and x, y)?

Deer530
  • 73
  • 1
  • 1
  • 10

1 Answers1

2

You can use sorted to sort the original list, then use list slicing to get the first two and last two elements of the sorted list.

>>> list1 = ['a', 'y', 'k', 'x', 'd', 'l']
>>> sorted_list = sorted(list1)
>>> new_list = sorted_list[0:2] + sorted_list[-2:]
>>> new_list
['a', 'd', 'x', 'y']
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Can you explain why you split it from 0:2 and -2? I would expect it's 0:1 and -2:-1 – Deer530 Oct 04 '15 at 15:56
  • @Deer530 Slicing (and many other operations in Python) is ["half-open"](https://stackoverflow.com/questions/11364533/why-are-slice-and-range-upper-bound-exclusive) meaning it does not include the last index. – Cory Kramer Oct 04 '15 at 15:57
  • But wouldn't 0:2 include the 3rd term alphabetically? – Deer530 Oct 04 '15 at 16:01
  • No, I just said it does *not* include the last index. The range `[0:2]` includes `[0]` and `[1]`. – Cory Kramer Oct 04 '15 at 16:02