I need to pass a user input variable as this list eg: [1, 3, 6, 4, 1, 2] in below python program. Could some one help me

Viewed 77
def solution(A):
    sortedset= set(sorted(A))
    sol=1
    #for i in sortedset
    print(sortedset)
    for i in sortedset:
        if i == sol:
           sol+=1
        else:
            break
    print(sol)
A = input()
solution(A)

#A = [1, 3, 6, 4, 1, 2]

''While passing A = input() and input [1,3,6,4,1,2] not getting expected output '5' but if I give instead of user input directly like as A = [1, 3, 6, 4, 1, 2] i'm getting output '5'. Please help me to fix this issue. ''

4 Answers

You can convert the string interpretation of a list that input returns to a list with ast.literal_eval:

import ast

A = ast.literal_eval(input())

As some people mentioned in the comments, the input function always returns a string.

However if you can always convert this string into your desired type. For example:

  1. Using a try block to handle the exception
A = []
  try: 
    while True:
      A.append(int(input()))
  # if the input is not-integer, run the function
  except:
    solution(A)
  1. Using list comprehension:
A = [int(item) for item in input("Enter the list items separated by space: ").split()]
solution(A)

This would work in python2 but not in 3 as the input is python 2's raw input and python 2's input has been removed

you could use eval(input()) instead

This is what you want I believe: i) string representation of list -> list ii) elements of list -> int

import ast
x = '[ "1", "2", "3" , "4", "5"]'
x = ast.literal_eval(x)
x = [int(val) for val in x ]
print(x)

[1, 2, 3, 4, 5]

Related