My issues:
- How is
(9,)
different from(9)
?(9,)==(9)
yieldsFalse
- Why is
(9,)
showing up in the snippet below? - How do I fix the code below so I get
(9)
?
chop_first_three = lambda t: t[3:] chop_first_three((1, 2, 3, 4, 5)) # (4, 5) correct chop_first_three(('abc', 7, 8, 9)) # (9,) ??? why not (9)?
Answer
The simple answer is, parentheses are overloaded for grouping and for tuples. To differentiate these forms in python, a trailing comma explicitly indicates a tuple.
Several answers and comments below point this out.
I’ve left my original questions above so the answers below make sense, but obviously, some of my original questions were incorrect.
Advertisement
Answer
In python if you wrap an object in parenthesis you will just get the element back.
a = (9) print(type(a)) # <class 'int'>
(9,)
instead is a tuple containing only one element (the number 9)
a = (9,) print(type(a)) # <class 'tuple'>
When you slice a tuple you will always get a tuple back (even if it only contains one element) Therefore the (9,)