Question

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

Was it helpful?

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']
>>>

OTHER TIPS

Using enumerate like this:

alist = ['aaaa', 'aaata', 'aaatt']
output = ['>{}/n{}'.format(idx, ele) for idx, ele in enumerate(alist, start=1)]

prints

['>1/naaaa', '>2/naaata', '>3/naaatt']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top