1

I have an input with newline between each string. The end will be noted by a number between 1 to 5:

Input: Ha

Ha

Hee

Hee

Ho

5

I need to accept this as list of strings in python where my list would contain: ['Ha', 'Ha', 'Hee', 'Hee', 'Ho']

After a lot of googling, I tried the following code:

lines = []

sentinel = range(6)

for i in iter(raw_input, [str(s) for s in sentinel]):
    if i=='':
        continue
    else:
        lines.append(i)

print lines

I don't know why but it goes into an infinite loop.

Please help me out!

1
  • What's the number at the end of the input for? Commented Sep 19, 2014 at 0:21

2 Answers 2

1

The issue is with the way iter() interpets the sentinel. It's a single value that indicates the end of iteration. For your sentinel to be hit, raw_input() would actually have to return an identical list, which can never happen (since of course it returns a str).

If you wrap things up a bit, you can make it work:

sentinel = range(6)

def anything_but(values):
    values = map(str, values)
    def inner():
        i = raw_input()
        if i in values:
            return None
        return i
    return inner

lines = []
for i in iter(anything_but(sentinel), None):
    lines.append(i)

print lines

In this case, None is the sentinel value which will be returned if a number 0-5 is entered. As an aside, if you wanted 1-5 as you mentioned you should use range(1, 6) instead.

However, you're probably better served doing it with a generator:

sentinel = range(6)

def anything_but(values):
    values = map(str, values)
    i = raw_input()
    while i not in values:
        yield i
        i = raw_input()

lines = []
for i in anything_but(sentinel):
    lines.append(i)

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

Comments

0

You can just use a while loop:

inp = raw_input()
while inp not in {"1","2","3","4","5"}:
    if not inp:
       continue
    else:
        lines.append(inp)
    inp = raw_input()
print lines

Using the inputs in your question outputs:

['Ha', 'Ha', 'Hee', 'Hee', 'Ho']

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.