Tired of writing multiple lines to convert string input into a list, tuple, or dictionary in Python?
Ever wondered if there's a shortcut to parse user inputs as-is?
Let’s unlock the underrated but powerfuleval()
function! ⚡
🧠 The Problem
You're building a CLI tool or a quick script and want to allow user input like:
[1, 2, 3] # List
(4, 5, 6) # Tuple
{"name": "bhuvanesh"} # Dictionary
Using input()
gives you strings — not the actual data types.
So instead of this:
data = input("Enter list: ")
# Now you need to manually parse or use json.loads()
Wouldn’t it be cool to directly get a list/tuple/dict?
✅ The Classic eval()
Solution
user_input = input("Enter any Python literal: ")
parsed = eval(user_input)
print(type(parsed), parsed)
🎯 Just like that, the input '[1, 2, 3]'
becomes a list object.
⚠️ Warning: Use with Caution
eval()
executes any code. So it's unsafe if the input comes from an untrusted source.
# Potentially dangerous
eval("__import__('os').system('rm -rf /')")
👮♂️ Use it only in controlled environments, like local scripts, learning, or quick utilities.
🔐 Safer Alternative: ast.literal_eval
If you're dealing only with basic Python literals, use:
import ast
safe_data = ast.literal_eval(input("Enter literal: "))
print(type(safe_data), safe_data)
✅ Safer
✅ No arbitrary code execution
✅ Handles strings, numbers, lists, dicts, etc.
🧪 Try These Examples
Input: [10, 20, 30] ➜ Output: <class 'list'> [10, 20, 30]
Input: (1, 2) ➜ Output: <class 'tuple'> (1, 2)
Input: {"id": 123} ➜ Output: <class 'dict'> {'id': 123}
Input: 'hello world' ➜ Output: <class 'str'> hello world
🏁 Quick Summary
✅ eval()
turns string input into real Python objects
⚠️ Risky with unknown input — use only when safe
✅ Use ast.literal_eval()
for secure parsing
🚀 Handy for quick data entry, debugging, or interactive tools
💬 Do you use eval()
in your projects? Prefer safer methods?
Let's discuss in the comments!
📖 More Python🐍 tips by @bhuvaneshm_dev
Keep exploring these small Python features that make a big impact in productivity!