user2851022
user2851022

Reputation: 9

The equivalent of eval() in python 2.7.5

We can use eval(input()) to allow the user to enter a list in python3 Here is an example:

  L = eval(input('Enter a list: '))
  print('The first element is ', L[0])
  Enter a list: [5,7,9]
  The first element is 5

But eval() not working in python2.7

I want to input data as a list [5,7,9] and want to take each value as L[0] is 5, L[1] is 7, etc. using python 2.7.

Upvotes: 1

Views: 1984

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

input() in Python 2 already applies eval().

Python 3 input() is Python 2's raw_input(), renamed. In Python 2, input() is the same thing as eval(raw_input()):

L = input('Enter a list: ')  # includes a call to `eval()` in Python 2

However, the better alternative is to use ast.literal_eval() instead; it only allows Python literals, while eval() allows arbitrary Python expressions. For taking a list input with numbers, ast.literal_eval() is plenty and not open to security issues:

from ast import literal_eval

L = literal_eval(raw_input('Enter a list: '))  # safe alternative to eval

Note that you still need to pass in valid Python literals; use ['a', 4, 7], not [a, 4, 7]; just a without quotes is not a valid Python string literal.

Upvotes: 7

user278064
user278064

Reputation: 10170

Just use input in python 2.7.5

lst = input("Enter a list:")  
>> [1,2,3]  # lst = [1,2,3]

lst[0]  # 5
lst[1]  # 7
...

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142156

Martijn's correct re: raw_input/input - but it's worth noting the approach that should be preferred on both for your example for safer evaluation of simple literals:

from ast import literal_eval
L = literal_eval(raw_input('Enter a list: ')) # or `input` for Python 3.x

Upvotes: 0

Related Questions