Home > Enterprise >  How to store two space-separated variables as one element in a list to output the element later as i
How to store two space-separated variables as one element in a list to output the element later as i

Time:10-31

I'd like to append two space-separated integer variables to a list as an element, then later output the contents of the list on newlines. For example,

storage = a   3, b   3
lst.append(storage)

Later, when printing the elements of the list, I get:

for i in lst:
   print(i)

>>> (4, 7)
>>> (3, 6)
>>> (7, 7)

Instead, I'd like the output to be exactly:

>>> 4 7 
>>> 3 6
>>> 7 7

separated on newlines as a space-separated pair of integers without commas and not part of a list. In addition, I also input singular integers between the pairs and would like to output them on a newline as well:

for i in lst:
    print(i)

Expected output:

>>> 1
>>> 4 7 
>>> 3 6
>>> -1
>>> 7 7
>>> 3

How can I do this without using list comprehension/mapping/defined functions/importing?

CodePudding user response:

Test each element to see if it's a tuple, and if it is, use the * operator to spread it as multiple args to print().

>>> lst = [1, (4, 7), (3, 6), -1, (7, 7), 3]
>>> for i in lst:
...     if isinstance(i, tuple):
...         print(">>>", *i)
...     else:
...         print(">>>", i)
...
>>> 1
>>> 4 7
>>> 3 6
>>> -1
>>> 7 7
>>> 3
  • Related