Python Forum
ternary operator with unpacking
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ternary operator with unpacking
#1
Hello,
After using ternary operators extensively I am getting lost in this case. It took me a couple of hours to understand why I was getting bugged, and though I've identified the cause I can't understand why this example works like this.

# pretty clear
a = [("1", "2"), ("", "")]
b, c = list(zip(*a))
print(b)
print(c)
('1', '')
('2', '')
# here I would expect the same as before, however...
a = [("1", "2"), ("", "")]
b, c = list(zip(*a)) if True else [""], [""]
print(b)
print(c)
[('1', ''), ('2', '')]
['']
# this result is expected but why it differs from the second?
a = [("1", "2"), ("", "")]
b, c = list(zip(*a)) if True else ([""], [""])
print(b)
print(c)
('1', '')
('2', '')
Would someone be willing to comment on this? Smile

EDIT: after posting the thread and staring at it, a spark came... ternary operator ended with the comma... so [""] was passed to c even when condition evaluates to True
Reply


Messages In This Thread
ternary operator with unpacking - by joaomcteixeira - Jan-07-2019, 11:21 AM
RE: ternary operator with unpacking - by buran - Jan-07-2019, 11:34 AM
RE: ternary operator with unpacking - by buran - Jan-07-2019, 12:30 PM
RE: ternary operator with unpacking - by perfringo - Jan-08-2019, 07:05 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Unpacking a dict with * or ** msrk 4 995 Dec-02-2023, 11:50 PM
Last Post: msrk
  iterate through the dict_values while unpacking the dictionary PeacockOpenminded 3 1,310 Jan-22-2023, 12:44 PM
Last Post: PeacockOpenminded
Thumbs Up Python 3 Jupyter notebook ternary plot data nicholas 0 940 Jan-21-2023, 05:01 PM
Last Post: nicholas
  Unpacking zip object Mark17 12 3,237 Mar-28-2022, 04:59 PM
Last Post: deanhystad
  unpacking list wardancer84 2 1,888 Sep-11-2021, 02:42 PM
Last Post: wardancer84
  unpacking tuple not working project_science 1 1,494 Jan-09-2021, 09:09 PM
Last Post: buran
  Unpacking a list Mark17 3 2,619 Dec-18-2020, 05:08 AM
Last Post: aajkaal
  Unpacking wheel files DavidTheGrockle 3 11,386 Dec-15-2020, 05:11 PM
Last Post: DavidTheGrockle
  how to return False in ternary condition KEYS 7 3,058 Dec-10-2020, 05:32 PM
Last Post: perfringo
  Why the result of "extended iterable unpacking" with set() is unpredictable? zohanlin 2 2,073 Jun-29-2020, 10:30 AM
Last Post: zohanlin

Forum Jump:

User Panel Messages

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