Home > Enterprise >  How to create a tuple with a string and an int?
How to create a tuple with a string and an int?

Time:08-09

input:

animal: 'cat'
number: 8

output:

('cat', 8)

I tried to do this:

tuple(animal, number)

but it gives me an error saying i have 2 arguments instead of 1.

I tried to do this then:

tuple[animal, number]

but I get this:

tuple['cat', 8]

can someone help me?

CodePudding user response:

As mentioned in the comments, if you want to tuple() you need to provide an iterable e.g.,

>>> animal = 'cat'
>>> number = 8
>>> tuple([animal, number])
('cat', 8)

or

>>> tuple((animal, number))
('cat', 8)

However, it may be easier and more readable to use the following:

>>> (animal, number)
('cat', 8)

Note that it is actually the comma which makes a tuple, not the parentheses:

>>> animal, number
('cat', 8)

CodePudding user response:

You just need to push animal and cat into a single list first, then create a tuple based on your list. tuple() takes only one argument, as that error indicates

animal = 'cat'
num = 8
mylist = [animal, num]
tuple(mylist)
  • Related