-2

I want to extract the elements as

list = [[1,3], [2,3], [3,4]] becomes
a = [1,3]
b = [2,3]
c = [3,4]

What if list contains more than 26 elements? I have written a function which uses sets and I want that function to work on this list also.

martianwars
  • 6,380
  • 5
  • 35
  • 44
Aaron
  • 37
  • 8
  • it's not optimal decision to unpack each item of a large list into separate variable – RomanPerekhrest Nov 24 '16 at 16:16
  • If you think you need to do this, you're thinking wrong. If the variables can change dynamically, how would you use them in the program, since it doesn't know which variables to look in. Just keep them in the list and access them from there. – Barmar Nov 24 '16 at 17:05
  • If all what you need is to associate a key with each sub list, what about storing your data in a dictionary? – ettanany Nov 24 '16 at 17:23

3 Answers3

0

I am not sure why do you want to store nested list in the variables. Instead I will suggest to access the values with index as:

>>> list = [[1,3], [2,3], [3,4]]
#        v list at index `0`
>>> list[0]
[1, 3]

However, if the number of elements in the nested list were fixed, you may unpacked the list and store it in variable as:

>>> a, b, c  = [[1,3], [2,3], [3,4]]
>>> a
[1, 3]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

Any reserved keyword in python cannot be used as a variable name. 'list' is a reserved keyword in python so you cannot use it as a variable name.

Instead of a,b,c you can use a1,a2,a3 to unpack the values.

The code below will unpack as many numbers in the list. It can be 26 or can be even more than that.

list1 = [[1,3], [2,3], [3,4]]

for i in xrange(0, len(list1)):
    exec("a%d = %s" % (i + 1, repr(list1[i])));

print a1
print a2
print a3

Output:

[1, 3]
[2, 3]
[3, 4]

Source: generating variable names on fly in python

Community
  • 1
  • 1
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
0

An easy way to do is:

list_variable = [[1,3], [2,3], [3,4]]
a, b, c  = list_variable
print(a)
print(b)
print(c)

Output:

[1, 3]
[2, 3]
[3, 4]
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44