How can I assign non-numerical Ids to list elements in Python?

Question:

I have a list of Strings and I want to assign to all of them a unique suffix as an Id as it follows:

Let’s asume that the list is ["str1", "str2", "str3"], I want to insert the Ids like this: ["str1-a", "str2-b", "str3-c"].

Is there any way of assigning these ids iteratively like:

id = a
for each element in the list:
    add the id to the string
    increment the id # from a to b, from b to c etc.

instead of getting each element in order and doing it three times?

In my case I know that there are less than 26 elements so the fact that the alphabet has only 26 letters is not a problem.

Thanks!!

Asked By: Julen

||

Answers:

There is a constant in the string module which has all the letters in a string, like 'abcdefg...'. See the docs.

from string import ascii_lowercase
new_list = []
for letter, element in zip(ascii_lowercase, old_list):
    new_list.append(element + '-' + letter)

Or, using a list comprehension:

new_list = [element + '-' + letter for letter, element in zip(ascii_lowercase, old_list)]
Answered By: The Thonnu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.