-1

if I have a list, say:

tags= ["ff", "uu", "ss"] 
        

However, I do not know how assign element liste to variable, knowing that the number of elements in the list is variable and i want to assign a None to tag4 and tag5

tag1, tag2, tag3, tag4 , tag5 = tags

2 Answers2

0
tags= ["ff", "uu", "ss"]
tag_vars={}

for i in range(len(tags)):
    tag_vars[f"tag{i+1}"] = tags[i]

print(tag_vars)
print(tag_vars["tag1"])
print(tag_vars["tag2"])
print(tag_vars["tag3"])
AthulMuralidhar
  • 662
  • 1
  • 9
  • 26
R242
  • 1
  • 1
0

i would do it like this:

tags= ["ff", "uu", "ss", None, None]
tag1, tag2, tag3, tag4 , tag5 = tags

Some explanation - if you have a fixed number of elements in the array, you can fill the rest with None values.

This works well for prototyping and small arrays but if you are working with ML and other fancy things, I suggest using numpy and or pandas for this sort of manipulations.

output is as follows:


In [6]: tag1
Out[6]: 'ff'

In [7]: tag2
Out[7]: 'uu'

In [8]: tag3
Out[8]: 'ss'

In [9]: tag4

In [10]: tag5

In [11]: tag5 is None
Out[11]: True

Here's another way to do it: initalize a list with your fixed number say 5 like and only place items in the particular indices, like so:

n [16]: l = [None] * 5

In [17]: l
Out[17]: [None, None, None, None, None]

In [18]: l[0] = 'foo'

In [19]: l
Out[19]: ['foo', None, None, None, None]

original answer: Create an empty list in Python with certain size

AthulMuralidhar
  • 662
  • 1
  • 9
  • 26