Home > Software design >  What is "if something[i]:" in python
What is "if something[i]:" in python

Time:11-11

I'm studying about Sieve of Eratosthenes in python and see a command is:

for p in range(n   1):
    if prime[p]:

So I want to ask you guys what is if something[p]: means. Because, during my learning python, it was not mentioned. Thanks for your help and sorry because my english so bad.

CodePudding user response:

something[p] slices the pth element of the iterable something, if ...: checks if this element is truthy (non null number, non empty string, True, etc.) and if this is the case, evaluates the block.

CodePudding user response:

In any if-statement in python the value to the right of the if is interpreted as a boolean value, and so:

if condition:
    ...

is exactly the same as:

if bool(condition):
    ...

in your case prime[p] is being interpreted as a boolean value. The exact behaviour depends on what prime[p] represents, and indeed what prime represents. Under the assumption that prime is a list (could in principle be other types, including dict but that would be a weird design decision!) and therefore prime[p] is the pth element of the list:

prime = [True, "some string value", "", None, 12.3, 1234, 0, False]

then:

  • bool(prime[0]) is True
  • bool(prime[1]) is True
  • bool(prime[2]) is False, since empty strings resolve to False
  • bool(prime[3]) is False, since None resolves to False
  • bool(prime[4]) is True
  • bool(prime[5]) is True
  • bool(prime[6]) is False, since 0 resolves to False
  • bool(prime[7]) is False, since False is False

For more information on how different non-boolean values are interpreted, I'd suggest looking a tutorial like this one.

  • Related