-1

Specifically, I've been trying to make a code that assigns the variable my_list to a non-list variable without any spaces or commas.

my_list= [3, 4, 5, 9]  # Has to be integers  
my_var= ' '  
...

Expected result at the end:

my_var = 3459  

However, the problem is that I am able to do the complete opposite, and with letters instead:

variable = 'hello'  
mylist = [ ]  
for item in variable:  
    mylist.append(item)   
print(mylist)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
David
  • 65
  • 1
  • 5

1 Answers1

1

So you need to convert your list into a string. You can use join() for that:

my_var = ''.join(str(x) for x in my_list)

From the docs:

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.


Or using map():

my_var = ''.join(map(str, my_list))

From the docs:

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.


Similarly, if you want my_var to be an int just do int(my_var)

Example:

>>> my_list= [3, 4, 5, 9]
>>> my_var = ''.join(str(x) for x in my_list)
>>> my_var
'3459'
>>> int(my_var)
3459
>>> my_var = ''.join(map(str, my_list))
>>> my_var
'3459'
>>> int(my_var)
3459