2

I want to limit the size of a list in python 2.7 I have been trying to do it with a while loop but it doesn't work

l=[]
i=raw_input()//this is the size of the list
count=0
while count<i:
    l.append(raw_input())
    count=count+1

The thing is that it does not finish the loop. I think this problem has an easy answer but I can't find it. Thanks in advance

3 Answers 3

2

I think the problem is here:

i=raw_input()//this is the size of the list

raw_input() returns a string, not an integer, so comparisons between i and count don't make sense. [In Python 3, you'd get the error message TypeError: unorderable types: int() < str(), which would have made things clear.] If you convert i to an int, though:

i = int(raw_input())

it should do what you expect. (We'll ignore error handling etc. and possibly converting what you're adding to l if you need to.)

Note though that it would be more Pythonic to write something like

for term_i in range(num_terms):
    s = raw_input()
    l.append(s)

Most of the time you shouldn't need to manually keep track of indices by "+1", so if you find yourself doing it there's probably a better way.

Sign up to request clarification or add additional context in comments.

Comments

1

That is because i has a string value type, and int < "string" always returns true.

What you want is:

l=[]
i=raw_input() #this is the size of the list
count=0
while count<int(i): #Cast to int
    l.append(raw_input())
    count=count+1

1 Comment

I think this and @DSM's answers are best for not suggesting to use input() with python2.7. Much better to take the raw input and try and convert to int. +1
0

You should try changing your code to this:

l = []
i = input() //this is the size of the list
count = 0
while count < i:
    l.append(raw_input())
    count+=1

raw_input() returns a string while input() returns an integer. Also count+=1 is better programming practice than count = count + 1. Good luck

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.