I am new at Python, I am trying to create two lists which take input from the user. Currently I have some working code but I believe it can still be enhanced and can be done in shorter way.
k1 = []
print("For 1st list enter")
for i in range(5):
a = int(raw_input("Enter your value"))
k1.append(a)
k2 = []
print("For second list enter")
for j in range(5):
b = int(raw_input("Enter your values"))
k2.append(b)
-
6This question is less about how do I solve a problem, and more about how can I make my code better... there is a stack exchange forum for that: codereview.stackexchange.com The nuance is subtle, though.E. Ducateme– E. Ducateme2017年08月10日 02:11:13 +00:00Commented Aug 10, 2017 at 2:11
4 Answers 4
If you want to maintain the user entering one number at a time, a list comprehension lets you write this very concisely:
list_of_lists = []
for i in range(2):
print ('For list {} enter: '.format(i+1))
list_of_lists.append([int(raw_input("Enter your value")) for query in range(5)])
Sample result:
[[0, 5, 3, 5, 3], [4, 5, 6, 4, 3]]
The next step is to learn to handle invalid input using exceptions.
Comments
You can prompt the user to enter a whitespace-delimited string of tokens, then split that string into a list of those tokens.
For example:
mylist = raw_input().split()
Since you appear to be interested in up to five integer tokens, we should convert the splitted string tokens to integers, and truncate the list with a slice:
mylist = map(int, raw_input().split())[:5]
Note that you will need to wrap the map around a list() if you are using Python 3.x.
Also - you may find the Code Review community better suited to questions similar to yours.
Comments
Input : 1 4 5 6 6 7 Space seperated
Then
data = map(int, raw_input().split())
If your Input : 1
2
4
5
There in each line then you must be having count.
count = 5
data = [ int(input()) for i in range(count)]
It is better to give space seperated inputs if it is going into single list.
Comments
List comprehensions:
In [283]: [int(raw_input("Enter your values")) for i in range(5)]
Enter your values1
Enter your values2
Enter your values3
Enter your values4
Enter your values5
Out[283]: [1, 2, 3, 4, 5]
Of course this assumes all of your input is going to be valid.
Otherwise something like:
def get_int():
try:
return int(raw_input("Enter a number: "))
except (KeyboardInterrupt, ValueError):
return get_int()
Added exceptions. You probably don't really want the KeyboardInterrupt there, but if you want to prevent them from escaping the loop until they give you 10 numbers...
In [291]: [get_int() for i in range(10)]
Enter a number: 1
Enter a number: 2
Enter a number: a
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 56
Enter a number: 7
Enter a number: 8
Enter a number: 3
Enter a number: a
Enter a number: f
Enter a number: g
Enter a number: dfd
Enter a number: df
Enter a number: df
Enter a number: df
Enter a number: df
Enter a number: a
Enter a number: 9
Out[291]: [1, 2, 2, 3, 4, 56, 7, 8, 3, 9]