Search code examples
pythonlistsortingextend

Python: How to create new list with certain alphabetized items from original list?


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)?


Solution

  • 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']