Adilicious
Adilicious

Reputation: 1713

Create a Python list filled with the same string over and over and a number that increases based on a variable.

I'm trying to create a list that is populated by a reoccurring string and a number that marks which one in a row it is. The number that marks how many strings there will be is gotten from an int variable.

So something like this:

b = 5
a = range(2, b + 1)
c = []
c.append('Adi_' + str(a))

I was hoping this would create a list like this:

c = ['Adi_2', 'Adi_3', 'Adi_4', 'Adi_5']

Instead I get a list like this

c = ['Adi_[2, 3, 4, 5]']

So when I try to print it in new rows

for x in c:
    print"Welcome {0}".format(x)

The result of this is:

Welcome Adi_[2, 3, 4, 5]

The result I want is:

Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5

If anybody has Ideas I would appreciate it.

Upvotes: 8

Views: 18866

Answers (4)

Pierre GM
Pierre GM

Reputation: 20339

You almost got it:

for i in a:
    c.append('Adi_' + str(i))

Your initial line was transforming the whole list a as a string.

Note that you could get rid of the loop with a list comprehension and some string formatting:

c = ['Adi_%s' % s for s in a] 

or

c = ['Adi_{0}'.format(s) for s in a] #Python >= 2.6

Upvotes: 12

kjp
kjp

Reputation: 3116

Using list comprehensions:

b = 5
a = range(2, b + 1)
c = ['Adi_'+str(i) for i in a]
for x in c:
    print"Welcome {0}".format(x)

Upvotes: 1

damzam
damzam

Reputation: 1961

Or all on one line:

>>> for s in ['Welcome Adi_%d' % i for i in range(2,6)]:
...     print s
... 
Welcome Adi_2
Welcome Adi_3
Welcome Adi_4
Welcome Adi_5

Upvotes: 0

surt91
surt91

Reputation: 71

Or as a list comprehension:

b = 5
a = range(2, b + 1)
c = ["Adi_" + str(i) for i in a]

Upvotes: 1

Related Questions