0

I'm pretty new to python and I'm stacked on a simple problem: i have a list:

mylist = [1, 2, 3, 4]

if I extract one element like this:

print(my_list[1:2])

I get a list of one element, but i cannot compute any calculus by treating it as a variable :

print(my_list[1:2]+1)

because i get the error:

Traceback (most recent call last): File "C:\...\test_tuple.py", line XX, in <module> print(my_list[1:2]+1) TypeError: can only concatenate list (not "int") to list

how do I convert this single element list to a variable?

2
  • 1
    Try my_list[1]. Commented Sep 9, 2022 at 12:30
  • since you are doing slicing you are getting another list as a result, if you want to obtain the first variable from that list, you need to do something like this, print(my_list[1:2][0]+1) Commented Sep 9, 2022 at 12:46

2 Answers 2

3

What you are doing, with :, is slicing. This means grabbing a piece of a list as a new list. What you want is just one index, which you can do be using:

mylist = [1, 2, 3, 4]
print(mylist[2]+1)

You can also turn a one element list into a variable by using:

mylist = [1, 2, 3, 4]
new_list = mylist[1:2]
print(new_list[0]+1)

Lastly you can also use numpy arrays on which you can perform calculations as if it were a normal number as follows:

import numpy as np

mylist = [1, 2, 3, 4]
new_arr = np.array(mylist[1:2])
print(new_arr+1)

of course the first solution is the best in this case, but sometimes other solutions can fit your problem better.

Sign up to request clarification or add additional context in comments.

Comments

0

You're error is about, you are adding number to [],

you need to add number to number like below code;

print(my_list[1:2+1])

print(my_list[2+1])

print(my_list[2]+1) ##here youre adding to the value like (my_list[2])3+1 that it will not give you error

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.