FreeLand FreeLand - 4 months ago 5
Python Question

for looping and appending into list

list = []

def lecture(x):
for x in range(1,x):
print 'lecture', x


so I have this code that gives the result of

lecture 1
lecture 2


for an input of
lecture(3)
. Now, when I change the code to

list = []

def lecture(x):
for x in range(1,x):
y = 'lecture', x
print y


i get an output of

('lecture', 1)
('lecture', 2)


Ultimately I would like to know why this is the case as I am trying to find a way of appending the first results, the:

lecture 1
lecture 2


into a list but I can't as I get a list with the lecture number separated from its number by a comma etc.

Answer

You are getting that strange notation because 'lecture', x is a tuple. A datatype which acts like a list, but a non-flexible list. You can't change them that easily. You have to use the +-operator instead of a comma to put those two values into one variable.

And putting values in a list is done with the append function.

list = []

def lecture(x):
    for x in range(1,x):
        y = 'lecture' + str(x)
        list.append(y);
lecture(5)

Also note: y = 'lecture' + str(x) the str(x) is to make sure the different datatypes (int and string) don't conflict. Because String + Int ain't possible.

  • 5 (Int) + 5 (Int) is 10.
  • 5 (String) + 5 (String) is 55.
  • But 5 (String) + 5 (Int) is an error.
Comments