0

So in python I have this tuple, or at least it SHOULD be a tuple:

    listOfNames = ([(name, 'male') for name in names.words('male.txt')] + [(name, 'female') for name in names.words('female.txt')])

Yet when I run type(listOfNames), it returns "list". But why? There are clearly parentheses on the outside. Is this some new convention I am not aware of?

  • 2
    A singleton tuple needs a trailing comma (e.g. `1,` or `(1, )`. Otherwise it’s just a parenthesized expression. – crcvd Mar 22 '21 at 03:04

1 Answers1

0

A single () with no separators passes through whatever is inside it

>>> "something"
'something'
>>> ("something")
'something'
>>> ("something",)
('something',)

To make a tuple, you need a trailing comma or to explicitly cast to a tuple tuple()

(x)   # just x
(x,)  # tuple containing x

If you want to create a tuple directly, you can skip creating the intermediate list, and form a generator expression

You actually already do this when forming the list in your question, but it may come with a different name

[x for x in my_iterable if some_condition(x)]       # list comprehension
(x for x in my_iterable if some_condition(x))       # generator expression
tuple(x for x in my_iterable if some_condition(x))  # tuple from generator
ti7
  • 16,375
  • 6
  • 40
  • 68