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!
Top comments (0)