Python Forum
How do I add a number to every item in a list? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How do I add a number to every item in a list? (/thread-30620.html)



How do I add a number to every item in a list? - john316 - Oct-28-2020

Hey Guys,

I;m wondering how could I add a number to every single item in a list.

So for example. test1, test2 test3, test4

If i would have a range from 1 to 9

and add it to words like: test, number, pencil, etc.

I would like to see

test1, test2, test3, test4, test5, test6

number1, number2, number3, number4, number5, number6.

I would like this as an input and not printing it out...

Could you please help me out?

kind regards,

John


RE: How do I add a number to every item in a list? - Marbelous - Oct-28-2020

I'm not sure I'm clear on what you're asking but here's a quick example of appending an integer to a string and generating a list of the results.

word_in = input("Enter a word to append to: ")
range_in = input("Enter the number of appended words: ")

res = []

for n in range(int(range_in)):
    res.append(word_in + str(n))

print(res)



RE: How do I add a number to every item in a list? - deanhystad - Oct-28-2020

I don't understand what you mean by "I would like this as an input and not printing it out." so this may not be what you want.
pencils = [f'pencil{a}' for a in range(1, 10)]
#or
tests = ['test'+str(a) for a in range(1, 10)]
#or
numbers = []
for a in range(1, 10):
    numbers.append('number'+str(a))