0

I am trying to take input from user something like this: [[1,2,3], 4, 5]. in which [1,2,3] in list type and 4 and 5 in int type.

how can I do this by input method?

here is my code but in which everything is in string type.

in_list = input("Enter your list :- ").split()
print(in_list)
print(type(in_list[0]))
print(type(in_list[1]))

output:-

Enter your list :- 1,2,3 4 5
['1,2,3', '4', '5']
class 'str'
class 'str'

Deep Ghodasara
  • 768
  • 1
  • 5
  • 9

5 Answers5

0

For inputs containing numbers or lists, it falls on the program to check and modify the string entered by the user to get the desired result.

For an input provided as the following: 1,2,3 4 5 as given in the example, you can modify the string and convert to int along the following lines Using either list comprehensions or maps.

in_list = input("Enter your list :- ").split()
print(in_list)

in_list[0] = [int(s) for s in in_list[0].split(',')] #split on comma, typecast to int, reassign to 0th index
in_list[1:] = [int(s) for s in in_list[1:]] #typecast remaining values to int

#Alternate syntax using map
#in_list[0] = list(map(int,in_list[0].split(',')))
#in_list[1:] = list(map(int, in_list[1:]))

print(in_list)
#Output:
[[1, 2, 3], 4, 5]
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
0

you can use eval:

inp = input("Enter your list :- ").strip()
inp = eval(inp)
Krishna
  • 6,107
  • 2
  • 40
  • 43
0

A bit longer but this is another option.

my_string is the user input, the method works also for this kind of input:

my_str = '1,2,3 4 5 7,8,9 10 11'

res = [ e.split(',') for e in my_str.split(' ') ]
for i, e in enumerate(res):
  if len(e) == 1:
    res[i] = int(e[0])
  else:
    res[i] = [ int(ee) for ee in e ]

print(res)
#=> [[1, 2, 3], 4, 5, [7, 8, 9], 10, 11]
iGian
  • 11,023
  • 3
  • 21
  • 36
0

Use ast.literal_eval() (as commented by Daniel Mesejo):

import ast
in_list = ast.literal_eval(input("Enter your list :- "))
print(in_list)
print(type(in_list[0]))
print(type(in_list[1]))

Output:

[[1, 2, 3], 4, 5]
<class 'list'>
<class 'int'>

In addition to ast.literal_eval(), another user suggested just using eval(), which also works. For a discussion on why it's safer to use ast.literal_eval(), refer to this related question: Using python's eval() vs. ast.literal_eval()?.

From the ast documentation:

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

leekaiinthesky
  • 5,413
  • 4
  • 28
  • 39
0
my_list=[]
temp_list=[]
n=int(input('Enter the size of list'))

for i in range(n):  #loop for number of sub-list in the list
    for j in range(0,2): #loop for number of elements in the sub-list
        temp_list.append(input())
    my_list.append(temp_list)
    temp_list=[] # to empty the list for next iteration

print(my_list)
Dhruv
  • 13
  • 7