This question is about design and readbility, not performance:
Is it more pythonic to initialize tuples with the tuple keyword, or just with parenthesis? Both do the same thing, but explicitly typing tuple is more verbose.
Here's two different cases of tuple initalization.
- From existing iterable
def myfunc(myarg: Iterable):
# "tuple" is explicitly typed out
mytuple = tuple(myarg)
def myfunc(myarg: Iterable):
# "tuple" is not explicitly typed out; only parenthesis are used
mytuple = ([myarg])
- Creating new tuple from literal
# "tuple" is explicitly typed out
mytuple = tuple([1, 2, 3, 4])
# "tuple" is not explicitly typed out; only parenthesis are used
mytuple = (1, 2, 3, 4)
Contradictorily, I know that it is more common to initialize lists without explicit;y typing list:
mylist = [1, 2, 3, 4] # "list" is not explicitly typed out; only brackets are used
# Rather than:
mylist = list([1, 2, 3, 4]) # "list" is explicitly typed out
Personally, I always explicitly type out tuple to make it easier to see that a tuple is being initialized. However, this contradicts my style (which is the more popular style) of initializing lists (without explicitly typing list.
In conclusion, I want to know which way of initializing tuples is more pythonic.
Apart from the subjective answers one may give to your questions, there are a few mistakes in the code that you present (see the end of this answer).
IMO,
tupleandlistare not for constructing tuples and lists by enumerating their elements. To do so, use parentheses and brackets, respectively:In fact, when defining a tuple, parentheses are not necessary:
but I think it's much clearer if you use parentheses.
Notice in particular the case of tuples with one element, where it's necessary to use a trailing comma (before the closing parenthesis).
It doesn't hurt to do the same for lists and, in general, it doesn't hurt to have a trailing comma both in lists and tuples; but in the case of tuples of one element the comma is necessary.
The usefulness of
tupleandlistis for constructing tuples and lists from other iterables (generators, tuples, lists, etc.), e.g.For lists, list comprehensions are arguably preferable when possible:
Notice also that there are three lines in your code that are wrong:
mytuple = (myarg)does not construct a tuple unlessmyargis already a tuple; these are just parentheses.mytuple = tuple(1, 2, 3, 4)raises aTypeError.list[1, 2, 3, 4]is not a list, just use the brackets (it's funny that this is legal syntax, as mentioned in the comments above, but this is off-topic).If you insist on using the words
tupleandlistwhen you enumerate the elements, here's (one version of) the correct syntax: