1

I have a list of floats as such:

list_of_numbers = [6.983508046396359, 3.1427777550591887, -24.42539243473745]

I wish to assign the list of floats into individual variables as such

w1 = 6.983508046396359
w2 = 3.1427777550591887
w3 = -24.42539243473745

How do i go about assigning them into the desired variables?

jpp
  • 159,742
  • 34
  • 281
  • 339
user8795870
  • 73
  • 1
  • 6
  • 1
    Why do you want them in variables? Variable count is predefined when writing the code. Lists or other data structures can expand as needed. – Reut Sharabani Jun 28 '18 at 14:16
  • 1
    You almost certainly don't want to do this. You want a dictionary. Having names floating around in the namespace is, at best, impractical. – roganjosh Jun 28 '18 at 14:16
  • give a look at Python unpacking feature – Tryph Jun 28 '18 at 14:17
  • really just want to retrieve the value... not for any other purpose – user8795870 Jun 28 '18 at 14:33
  • @user8795870, If an answer below helped, please consider [accepting](https://stackoverflow.com/help/someone-answers) it (green tick on left). – jpp Jul 13 '18 at 09:13

5 Answers5

2

Use sequence unpacking:

list_of_numbers = [6.983508046396359, 3.1427777550591887, -24.42539243473745]
w1, w2, w3 = list_of_numbers

If you have a variable number of variables, consider using a dictionary:

w = dict(enumerate(list_of_numbers, 1))

Then access, for example, the first float via w[1].

iacob
  • 20,084
  • 6
  • 92
  • 119
jpp
  • 159,742
  • 34
  • 281
  • 339
0

Creating a dictionary:

list_of_numbers = [6.983508046396359, 3.1427777550591887, -24.42539243473745]
d = {"w" + str(i+1): j for i,j in enumerate(list_of_numbers)}

This can be accessed thus:

d["w1"]
>>> 6.983508046396359
iacob
  • 20,084
  • 6
  • 92
  • 119
0

If you know that there will always be the same number of values, then unpacking is a good option:

w1, w2, w3 = list_of_numbers

If, on the other hand, you want to do this for arbitrary length lists of numbers, then I would suggest that you are taking the wrong approach. If you must name them, use a dictionary like @ukemi suggests.

lxop
  • 7,596
  • 3
  • 27
  • 42
0

If the number and the names of the variables is known, unpacking is enough:

w1, w2, w3 = list_of_numbers

If you pass a list longuer than the number of variables, last one will receive a sequence containing the unexpanded list of all remaining elements from the field, if the list is too short, you will get an exception.

If the number and the names of the variables is not known in advance, then you do not want to do that. It is certainly possible because Python if dynamic enough, but is is hard to build and to use when direct access to a list is much simpler.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
-1

if you've a small list

w1 = list_of_numbers[0]
w2 = list_of_numbers[1]
w3 = list_of_numbers[2]
Waqar
  • 93
  • 1
  • 2
  • 9