0

1) hi i want to create a program where the User can input strings and it add on as list.

eg cmd : "hello "
   cmd : "every "
   cmd : "one "
'hello' 'every ' 'one'

a = 0
while a < 3:
    b = str(raw_input("cmd : "))
    list1 = [b]
    a += 1

print list1

issue i am having is adding up string to list on every loop ! i am missing some logic argument for this to happen. these string i would like to assign later on to some function.

2 Answers 2

1

You need an append list1 += [b] instead of assignment list1 = [b]

And in Python in this case its better to use for in. Also raw_input would return a string, you do not need to convert it

for a in range(3):
    b = raw_input("cmd : ")
    list1 += [b]

Or even better to use list comprehension as there is an overhead for appending a list.

list1 = [raw_input("cmd : ") for _ in range(3)]
Sign up to request clarification or add additional context in comments.

2 Comments

I think it would be more pythonic to use list1.append(b) (should be more efficient also since the [b] object doesn't have to be created.)
List1 = [] for a in range(2): b = raw_input("cmd :") List1.append(b) a += 1 print List1
0
List1 = []
for a in range(2):
    b = raw_input("cmd :")
    List1.append(b)
    a += 1
print List1

After going through the forum answer and by "korylprince" this is the code i come-up with which do exactly what i wanted.

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.