Can I sort by index?

QuestionsQuestions4 SkillsProPandas Sorting DataSep, 21 2025
0127

Yes, you can sort by index in a list of words or strings. Here's an example in Python that sorts words based on a specific character index:

def sort_words_by_char(words, index):
    for i in range(len(words)):
        for j in range(i + 1, len(words)):
            if words[i][index - 1] > words[j][index - 1]:
                words[i], words[j] = words[j], words[i]
    return words

words = ["banana", "apple", "cherry", "date"]
index = 2  # Sort by the second character
sorted_words = sort_words_by_char(words, index)
print(sorted_words)

In this example, the sort_words_by_char function sorts the list of words based on the character at the specified index (1-based). Adjust the index variable to sort by different character positions.

0 Comments

no data
Be the first to share your comment!