# Python | Sort alternate numeric and alphabet list

Sometimes, while performing sorting in list, we have a problem in which we need to perform particular type of sorting in which we need to sort in alternate ways in which we have numerics and alphabets sorted in order. Lets discuss certain ways in which this task can be performed.

Method #1 : Using isalpha() + isnumeric() + zip_longest() The combination of above methods can be used to perform this task. In this, we separate the numeric and alphabets and then perform a sort on them separately and join using zip_longest().

## Python3

 `# Python3 code to demonstrate ``# Sort alternate numeric and alphabet list``# using isalpha() + isnumeric() + zip_longest()``from` `itertools ``import` `zip_longest` `# Initializing list``test_list ``=` `[``'3'``, ``'B'``, ``'2'``, ``'A'``, ``'C'``, ``'1'``]` `# printing original list``print``("The original ``list` `is` `: " ``+` `str``(test_list))` `# Sort alternate numeric and alphabet list``# using isalpha() + isnumeric() + zip_longest()``num_list ``=` `sorted``(``filter``(``str``.isnumeric, test_list), ``                       ``key ``=` `lambda` `sub: ``int``(sub))` `chr_list ``=` `sorted``(``filter``(``str``.isalpha, test_list))``res ``=` `[ele ``for` `sub ``in` `zip_longest(num_list, chr_list)``                              ``for` `ele ``in` `sub ``if` `ele]``    ` `# printing result ``print` `("``List` `after performing sorting : " ``+` `str``(res))`

Output :
```The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']```

Method #2 : Using sorted() + key + lambda + isnumeric() The combination of above methods can be used to perform this task. In this, we perform the sorting in alternate manner using ord() and lambda function, testing using isnumeric().

## Python3

 `# Python3 code to demonstrate ``# Sort alternate numeric and alphabet list``# using sorted() + key + lambda + isnumeric()``from` `itertools ``import` `zip_longest` `# Initializing list``test_list ``=` `[``'3'``, ``'B'``, ``'2'``, ``'A'``, ``'C'``, ``'1'``]` `# printing original list``print``("The original ``list` `is` `: " ``+` `str``(test_list))` `# Sort alternate numeric and alphabet list``# using sorted() + key + lambda + isnumeric()``res ``=` `sorted``(test_list, key ``=` `lambda` `ele : (``int``(ele), ``0``)``      ``if` `ele.isnumeric()``      ``else` `((``ord``(ele) ``-` `64``) ``%` `26``, ``1``))` `# printing result ``print` `("``List` `after performing sorting : " ``+` `str``(res))`

Output :
```The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']```

Method #3:

• Split the list into two lists: one for digits and one for characters.
• Sort the lists using the built-in sort() function.
• Interleave the sorted lists and create the final result list.

## Python3

 `# Python3 code to demonstrate``# Sort alternate numeric and alphabet list` `# Initializing list``test_list ``=` `[``'3'``, ``'B'``, ``'2'``, ``'A'``, ``'C'``, ``'1'``]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `# Split the list into digits and characters``digits ``=` `[x ``for` `x ``in` `test_list ``if` `x.isdigit()]``chars ``=` `[x ``for` `x ``in` `test_list ``if` `x.isalpha()]` `# Sort the lists``digits.sort()``chars.sort()` `# Interleave the sorted lists``res ``=` `[``None``] ``*` `len``(test_list)``for` `i ``in` `range``(``len``(test_list)):``    ``if` `i ``%` `2` `=``=` `0``:``        ``res[i] ``=` `digits[i``/``/``2``]``    ``else``:``        ``res[i] ``=` `chars[i``/``/``2``]` `# printing result``print` `(``"List after performing sorting : "` `+` `str``(res))`

Output
```The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']```

Time complexity: O(nlogn)

Auxiliary Space:O(n)

Method #4: Using a custom sorting algorithm

1. Define a function custom_sort that takes an element ele and returns a tuple (key, value) where key is a string representing the type of the element (digit or character) and value is the element itself.
2. Use the sorted function to sort the list test_list using the custom_sort function as the key.
3. Create two empty lists digits and chars.
4. Iterate through the sorted list res and append the elements to either the digits list or the chars list, depending on their type.
5. Use the zip function to combine the digits and chars lists into a single list.
6. Use the itertools.chain.from_iterable function to flatten the combined list.
7. Convert the flattened list back to a string using the join function.

## Python3

 `import` `itertools` `def` `custom_sort(ele):``    ``if` `ele.isnumeric():``        ``return` `(``'digit'``, ``int``(ele))``    ``else``:``        ``return` `(``'char'``, ele)` `# Initializing list``test_list ``=` `[``'3'``, ``'B'``, ``'2'``, ``'A'``, ``'C'``, ``'1'``]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `# Sort alternate numeric and alphabet list using custom sorting algorithm``res ``=` `sorted``(test_list, key``=``custom_sort)` `# Create two lists for digits and characters``digits ``=` `[]``chars ``=` `[]` `# Append elements to either digits or chars list depending on their type``for` `ele ``in` `res:``    ``if` `ele.isnumeric():``        ``digits.append(ele)``    ``else``:``        ``chars.append(ele)` `# Combine digits and chars lists into a single list``combined ``=` `list``(``zip``(digits, chars))` `# Flatten the combined list``result ``=` `list``(itertools.chain.from_iterable(combined))` `# Convert the flattened list back to a string``result_str ``=` `''.join(result)` `# printing result``print``(``"List after performing sorting : "` `+` `str``(result))`

Output
```The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']
```

Time complexity: Sorting the list takes O(n log n) time using the sorted function, where n is the length of the list. Iterating through the sorted list takes O(n) time. Combining and flattening the lists takes O(n) time. Therefore, the overall time complexity is O(n log n).

Auxiliary space: We create two additional lists (digits and chars) and one additional tuple list (combined), each with a maximum size of n/2, where n is the length of the input list. Therefore, the auxiliary space complexity is O(n).

Previous
Next
Share your thoughts in the comments
Similar Reads