Python Forum
parenthesis around a tuple of literals in a for
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
parenthesis around a tuple of literals in a for
#1
is parenthesis required around a tuple of literals in a for?

i'm running into this:

Output:
>>> for x in 1,2,3: ... print(x) ... 1 2 3 >>> [x for x in 1,2,3] File "<stdin>", line 1 [x for x in 1,2,3] ^ SyntaxError: invalid syntax >>>
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
, outside of data structure like eg list it will always make a tuple.
>>> 1, 2
(1, 2)

>>> 'hello', 'world'
('hello', 'world')
So for x in 1,2,3: is just the same as for x in (1,2,3):

In a list is , parsed as separator,then 1, 2, 3 is three separate element and not a tuple.
For it to be a tuple or list inside a list comprehension then have to make it so () [].
>>> [x for x in (1,2,3)]
[1, 2, 3]

>>> [x for x in [1,2,3]]
[1, 2, 3]
Reply
#3
so you have to put the , deeper in whatever you want it to be in, because in a comprehension it is already in something that will apply to it.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why does Python not use parenthesis to contain loops? davidorlow 3 3,400 Jun-09-2021, 06:33 AM
Last Post: Gribouillis
  replace in code vs literals Skaperen 3 2,398 Mar-30-2021, 12:37 AM
Last Post: Skaperen
  code with no tuple gets : IndexError: tuple index out of range Aggam 4 2,729 Nov-04-2020, 11:26 AM
Last Post: Aggam
  What Are Python Literals? Julie 11 4,343 Sep-23-2020, 05:31 PM
Last Post: Gribouillis
  string literals in a list. Not what I expected. tycarac 3 2,633 Dec-28-2019, 05:31 AM
Last Post: tycarac
  Parenthesis in User-Defined Functions giorgitsu 2 1,940 Aug-07-2019, 12:56 PM
Last Post: ThomasL
  How to get first line of a tuple and the third item in its tuple. Need Help, Anybody? SukhmeetSingh 5 3,122 May-21-2019, 11:39 AM
Last Post: avorane
  a Word Inside Parenthesis in Class Decleration tahasozgen 2 2,496 Dec-18-2018, 05:59 AM
Last Post: Gribouillis
  Escaping whitespace and parenthesis in filenames jehoshua 2 9,636 Mar-21-2018, 09:12 AM
Last Post: jehoshua

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020