Search code examples
pythonlistappendprepend

Append/Prepend a different character to each item in a list


Starting with a list such as:

['aaaa', 'aaata', 'aaatt'] 

How could I prepend a different character to that start of each item denoting its order, i.e. produce a list that went:

['>1/naaaa', '>2/naaata', '>3/naaatt'] 

Thank you


Solution

  • You can use a list comprehension with enumerate:

    >>> lst = ['aaaa', 'aaata', 'aaatt']
    >>> [">{}/n{}".format(x, y) for x,y in enumerate(lst, 1)]
    ['>1/naaaa', '>2/naaata', '>3/naaatt']
    >>>
    

    Edit:

    Regarding your comment, all you need is string.ascii_lowercase:

    >>> from string import ascii_lowercase
    >>> ascii_lowercase  # Just to demonstrate
    'abcdefghijklmnopqrstuvwxyz'
    >>> lst = ['aaaa', 'aaata', 'aaatt']
    >>> [">{}/n{}".format(ascii_lowercase[x], y) for x,y in enumerate(lst)]
    ['>a/naaaa', '>b/naaata', '>c/naaatt']
    >>>