Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
looping through lists
#1
I have just started to learn Python and am going through tutorial. I have the following iteration:
[(x,y,z) for x in [1, 2, 3] for y in [1, 2, 3] for z in [1, 2, 3] if x != y & x != z & y != z]

The answer I get is:
[(1, 2, 3), (2, 1, 3), (3, 1, 2), (3, 2, 1)]

I was wondering why I should not get (2, 3, 1) and (1, 3, 2) as part of my answer.

Thanks,
Reply
#2
& is bitwise and
it is not quite the same as boolean and

>>> [(x,y,z) for x in [1, 2, 3] for y in [1, 2, 3] for z in [1, 2, 3] if x != y & x != z & y != z]
[(1, 2, 3), (2, 1, 3), (3, 1, 2), (3, 2, 1)]
>>> [(x,y,z) for x in [1, 2, 3] for y in [1, 2, 3] for z in [1, 2, 3] if x != y and x != z and y != z]
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
Reply
#3
Great! Thanks! it helped a lot.
I have not reached that section of the tutorial explaining logical And, etc. yet! I was just experimenting!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Populate the new lists by looping over the original lists drunkenphd 1 1,496 Oct-10-2020, 02:54 AM
Last Post: Skaperen
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,312 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  How to concatenate files while looping through lists? python_newbie09 3 2,822 Mar-24-2019, 03:11 PM
Last Post: python_newbie09
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,186 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

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