-3
x=[[1.0, -1.0, 0.0, 3.0], [1.0, 2.0, 3.0, 4.0], ...]

x is a nested list

Expected o/p:

x1=[1.0, -1.0, 0.0, 3.0]
x2=[[1.0, 2.0, 3.0, 4.0]

further i will be using x1, x2, ... separately in different functions. E.g.

x_add=x1+x2

I tried using loop but was not able to get expected o/p I want the loop to iterate up to length of x and extract each sub list from list x and assign it to a variable xn iteratively.

Ari Cooper-Davis
  • 3,056
  • 1
  • 25
  • 41
  • 3
    Do you know how many variables you're trying to assign (i.e. the length of the list `x`)? – Ari Cooper-Davis Aug 23 '21 at 16:06
  • 1
    Welcome to SO! Only unpack the list if it's 2-3 variables. Anything more than that or if the number of elements are unknown and you want to unpack all of them, [keep it a list](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables). See [unpack the first two elements in list/tuple](https://stackoverflow.com/questions/11371204/unpack-the-first-two-elements-in-list-tuple) – ggorlen Aug 23 '21 at 16:08

1 Answers1

1

If you know the length of list x you can assign its contents to variables like so:

x = [[1, 2, 3], [4, 5, 6]]
x1, x2 = x
print(x1) # [1, 2, 3]
print(x2) # [4, 5, 6]

If you don't know the length of list x you're almost certainly better off not trying to approach your problem in this way! So, having warned you that this really isn't a good idea, you can do it using exec():

x = [[1, 2, 3], [4, 5, 6]]
for i, _x, in enumerate(x):
   exec(f"x{i+1} = _x")

print(x1) # [1, 2, 3]
print(x2) # [4, 5, 6]

This is a significant security risk, will make your code very hard to read and debug, is not a good use of variable types, and should absolutely be avoided.

Ari Cooper-Davis
  • 3,056
  • 1
  • 25
  • 41