0
[['1', '2', '0'], ['1', '2', '2'], ['1', '2', '5'], ['1', '2', '6']]

I have a list of list as shown above, and I want to set variables and get the value of 3rd index from each list into the variable. What's the most efficient way to set it automatically?

I can have something like

list1=0
list2=0
list3=0
list4=0
for i in s:
     list1 = i[2]

But in this scenario, I'm specifying the list1,2,3,4. I want it to increment up and just get 3rd index data into it.

For instance, For the list of lists above, I want to set list1, list2, list3, list4..

Then 
list1 = '0'
list2 = '2'
list3 = '5'
list4 = '6'

Rather than me specifiyng list1,list2,list3,list4, what's best method to list and set variables and values on its own from the list of list?

List of list could be changing in size. It could be more than 4 lists in there.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • instead of `list1`, `list2` use list - `values = []` - and `append()` - `for i in s: values.append(i[2])` – furas Jun 28 '19 at 00:35
  • Anytime you are tempted to try to automatically create variables with increasing numbers like `list1` `list2` is is a sure sign you want a list, which you then use with `my_list[0]`, `my_list[1]` etc. – Mark Jun 28 '19 at 00:43
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – snakecharmerb Jun 29 '19 at 08:53

3 Answers3

2

You can store the third element of eachsub list in a new list:

list = [['1', '2', '0'], ['1', '2', '2'], ['1', '2', '5'], ['1', '2', '6']]

newList = [x[2] for x in list]

print(newList) # ['0', '2', '5', '6']

Storing the third element of each sublist in a new variable such as list1, list2, list3, list4 is not only inconvenient, but straight up not an option if you don't know how many elements your original list will have ahead of time.

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
1

I am recommend save them into a dict

d={'List'+str(x+1) : y[2]for x, y in enumerate(l)}
d
{'List1': '0', 'List2': '2', 'List3': '5', 'List4': '6'}
BENY
  • 317,841
  • 20
  • 164
  • 234
1

The best way would be to use a dictionary:

variables = {}
list_of_lists = [['1', '2', '0'], ['1', '2', '2'], ['1', '2', '5'], ['1', '2', '6']]

for i in range(len(list_of_lists)):
    variables['list{}'.format(str(i+1))] = list_of_lists[i][2]

>>> variables
{'list4': '6', 'list1': '0', 'list3': '5', 'list2': '2'}

Not recommended at all, but more accurate to what you were thinking of, is to use exec:

list_of_lists = [['1', '2', '0'], ['1', '2', '2'], ['1', '2', '5'], ['1', '2', '6']]

for i in range(len(list_of_lists)):
    exec('list{}={}'.format(str(i+1), list_of_lists[i][2]))

>>> list1
0
>>> list2
2
>>> list3
5
>>> list4
6
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76