0

Below is the code:

for x in range(0, 7) + 100:
    print x

Expected output:

 0
 1
 2
 3
 4
 5
 6
 100

Please help me get this output.

Below is the error of the code:

TypeError: can only concatenate list (not "int") to list
0

1 Answer 1

3

Since you are using Python 2, range is creating a list. To add a number to the end of a list, first put it in a list, then you can use the addition operator:

for x in range(0, 7) + [100]:

(To do this in python 3, you will need to convert the range into a list, as it range(...) creates a different datatype):

for x in list(range(0, 7)) + [100]:
Sign up to request clarification or add additional context in comments.

2 Comments

@idjaw No, I knew it would work, but I just tested it and it worked as expected.
I just saw the python2.7 tag. Right! In Python 2.7 range actually creates a list. That's why that works. In Python 3 that is not the case since it carries over the functionality of what xrange does in Python 2. Doing that in Python 3 will result in: TypeError: unsupported operand type(s) for +: 'range' and 'list'. Even though the tag states Python2.7, it might help to provide some of that detail in the answer considering it could be easily missed by future readers.

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.