Home > Software design >  Join list and string into a tuple of four elements
Join list and string into a tuple of four elements

Time:10-27

I have a list of nums:

[18, 9, 7]

and a string:

line = 'random text.'

I must join these two into a tuple of four elements shown below:

(18, 9, 7, 'random text.')

So far I have tried nums.join(line) but this does not work

How can I do this?

Note: I would prefer not using tuple() or importing anything. simplest most brute force method possible ;P

CodePudding user response:

You can unpack the list within the tuple declaration:

nums = [18, 9, 7]
line = 'random text.'
combined_tuple = (*nums, line)
print(combined_tuple)

Output:

(18, 9, 7, 'random text.')

CodePudding user response:

The absolute simplest method is the following:

lst = [18, 9, 7]
line = 'random text.'
tup = (lst[0], lst[1], lst[2], line)

CodePudding user response:

I think you need something like this

nums = [18, 9, 7]
line = 'random text.' 

result = (*[item for item in nums], line)

print(result)
  • Related