Python | Alternate Sort in String list

Sometimes, while working with Python list, we can have a problem in which we need to perform sorting only of alternatively in list. This kind of application can come many times. Let’s discuss certain way in which this task can be performed.

Method : Using join() + enumerate() + generator expression + sorted()
This task can be achieved by using combination of functionalities above. In this, we perform the sort using just %2 elements in String list. The extension of this operation to entire list is performed by generator expression.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Alternate Sort String list 
# using join() + enumerate() + generator expression + sorted()
  
# initialize list 
test_list = ['cdab', 'gfeh', 'kjil']
  
# printing original list 
print("The original list : " + str(test_list))
  
# Alternate Sort String list 
# using join() + enumerate() + generator expression + sorted()
res = ["".join(sorted(j, reverse = i % 2)) for i, j in enumerate(test_list)] 
  
# printing result
print("The String list after alternate sorting : " + str(res))

chevron_right


Output :

The original list : ['cdab', 'gfeh', 'kjil']
The String list after alternate sorting : ['abcd', 'hgfe', 'ijkl']
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.