0

My code if to flatten a shllow list:- I am getting an error of

int object is not subscriptable

l = eval(input("Enter a nested list : "))
a = len(l)
for x in range(0,a):
     a[x]+=a[x]
print(l)
5
  • a = len(l) a is an integer. a[x] makes no sense. Did you mean l[x]? Commented Jun 23, 2019 at 4:36
  • what'a shallow list? a 2D list? Commented Jun 23, 2019 at 4:37
  • It's easier for us to help you if you show the specific input you're using instead of using input. You probably mean l[x] instead of a[x]. Commented Jun 23, 2019 at 4:37
  • eval is dangerous to use with user inputs. Commented Jun 23, 2019 at 4:37
  • @Austin Yes, and yet in Python 2 input() meant eval(input()). Looking backwards it was almost stupid :) Although, I'd say eval is pretty fine as long as it doesn't appear in production code, and is used as a way to quickly test language features. That said, if the goal is just to parse some nested list of integers, floats, or strings, json.loads(input()) might be best. Commented Jun 23, 2019 at 4:54

3 Answers 3

1

Use below code:

l = list(map(int, input("Enter a nested list : ").split()))
total = 0
for i in l:
    total += i

print(total)

Output

Enter a nested list : 1 2 3
6
Sign up to request clarification or add additional context in comments.

Comments

0

First take the input as a string by str() then after you have stored it in l, convert it to a list using the list().

You can also directly convert the input to a list by list(input("text"))

1 Comment

It will be helpful if you can provide some code to the OP to provide how whatever you have described works
0
l =list( map( int, input("Enter a nested list : ").split() ))
print(sum(l))

1). Here you have to input values after pressing space, like 25 then press space then next number and so on.

2). It will give you the sum of the list, which is the same as flatten of the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.