0
About create tuples [Solved]
Why can I create tuple in this way, tup = (777) but not in that way? tup = tuple(777)
3 Réponses
+ 3
your first example does not create a tuple.
your second example gives an error because we must pass an iterable to tuple().
some examples:
x = (7) # int
print(x, type(x))
x = (7,)
print(x, type(x)) # tuple
x = tuple((7,))
print(x, type(x)) # tuple
x = tuple(7) # error as constructor expects an interable
print(x, type(x))
+ 3
Hey! đ
I see youâre trying to create a tuple in Python.
Hereâs the thing:
tup = (777) is NOT a tuple, it's just the number 777.
Check it: print(type(tup)) # <class 'int'>
To make a tuple with one item, you have two ways:
1ïžâŁ Using a comma inside parentheses:
tup = (777,)
2ïžâŁ Using tuple() on an iterable (like a list):
tup = tuple([777])
Tip: In Python, parentheses alone donât make a tupleâ**the comma does!**
Good luck with learning Python, itâs an awesome language! đ
+ 3
tuples always need to have the comma.
even 1 element needs the comma.
no comma, no tuple.
tup = 1,
print(type(tup)) # tuple
tup = 1,2,3
print(type(tup)) # tuple