Home > database >  python extract variable from a list
python extract variable from a list

Time:09-09

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?

CodePudding user response:

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[0] 1)

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

CodePudding user response:

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
  • Related