1

Write a function, which would return a list with the strings and their index. e.g. ['good', 'morning'] -> ['0 - good', '1 - morning']

I tried this:

def add_index(list_a):

    x = []
    for word in list_a:
        x = [list_a.index(word) for word in list_a]

    return x

However, the return is [0, 1], not what I am looking for.

0

4 Answers 4

4

You can use enumerate function:

>>> def f(data):
...     return ['{} - {}'.format(i, s) for i, s in enumerate(data)]
... 
>>> f(['good', 'morning'])
['0 - good', '1 - morning']

If you are in python 3.6+ you can also use f-strings:

>>> def f(data):
...     return [f'{i} - {s}' for i, s in enumerate(data)]
... 
>>> f(['good', 'morning'])
['0 - good', '1 - morning']
Sign up to request clarification or add additional context in comments.

Comments

1
x = []
for word in list_a:
    x = [list_a.index(word) + ' - ' + word  for word in list_a]

return x

Comments

0

Your list comprehension is only pulling the index and not the word:

x = ["{} - {}".format(list_a.index(word), word) for word in list_a]

Comments

0

Try doing this:

for index, word in enumerate(list_a):
    print(str(index) + " - " + word)

This will add an index number for every topic in list_a. That index is then added into a string printing it. If you want it to be added to a new list I would do like this.

x = []
for index, word in enumerate(list_a):
    x.insert(len(x), str(index) + " - " + str(word))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.