Python: understanding a list of weird behavior

Why is this code:

x = {"first":(True, "first description"), "second":(False, "second description")}
items = ["first", "second"]

for element in [k in x and x[k][0] for k in items]:
    print element

seal

  • True
  • False

instead of items in the "items" -list that match the expression

k in x and x[k][0]
+4
source share
4 answers

You print the result of the expression k in x and x[k][0].

It will either be False(if the result of the condition k in xis false) or the result x[k][0](if the result k in xwas true). Since it x[k][0]is a Boolean object in your input example, you will always get boolean values ​​here; nowhere in this case will the list be displayed.

If you want to filter, use the statement ifafter the loop:

[k for k in items if k in x and x[k][0]]

k, true, ['first'], True.

+4

[k in x and x[k][0] for k in items] k in x and x[k][0] items, True , .

, , :

[k for k in items if k in x and x[k][0]]
+3
x = {"first":(True, "first description"), "second":(False, "second description")}
items = ["first", "second"]

for element in [k in x and x[k][0] for k in items]:
    print element

, .

[k in x and x[k][0] for k in items]

. k == ['first', 'second']

1-

k = 'first'

['first' x (True) x ['first'] [0] (True)]

[True True]

[]

k = 'second'

- [True]

[True, "second" x (True) x ['second'] [0] (False)]

[True, True False]

[True, False]

,

for element in [True, False]:
    print element

,

True

False

.

+2

expression [k in x and x[k][0] for k in items] k in x and x[k][0], and , and, "sub-expression", falsy , . k in x, true, x[k][0], :

[True, False]

[k in x and x[k][0] for k in items], :

['first description', 'second description']

, , :

[k for k in items if k in x and x[k][0]]
0

Source: https://habr.com/ru/post/1674451/


All Articles