2

I was going through a code of tokenizing a tweet in python when I encountered the following piece of code. Note that tokens_re and emoticons_re are regex objects. Since tokenize(s) returns a list therefore tokens is a list. I am kind of new to python and I am not sure is the if-else running on the elements of list. The ternary operator as mentioned doesnt have the same syntax.

def tokenize(s):
    return tokens_re.findall(s)

def preprocess(s, lowercase=False):
    tokens = tokenize(s)
    if lowercase:
        tokens = [token if emoticon_re.search(token) else token.lower() for token in tokens]
    return tokens
6
  • 1
    I do not get what the question is. Commented Jun 25, 2017 at 11:05
  • how is he using the ternary operator on every element of the list in the given code? I am not able to understand how did he iterate every element of the list in the if block though he uses a for loop in else block Commented Jun 25, 2017 at 11:07
  • It works fine. In the list comprehension token loops over tokens, and for each value of token we have a ternary expression, the result of which is stored on the resulting list. Imagine parentheses around the termary. Commented Jun 25, 2017 at 11:09
  • @AndrasDeak he used a for loop in the else statement but not used any loop in the if statement how did he iterate over the list in the if statement? Commented Jun 25, 2017 at 11:10
  • 1
    @kartikeykant18: no the for is part of the list comprehension. The ternary operator has precedence over that. Commented Jun 25, 2017 at 11:12

2 Answers 2

5

The ternary operator has the same syntax:

[(token if emoticon_re.search(token) else token.lower()) for token in tokens]
#^              ternary operator expression            ^

So the for is not part of the else part of the ternary operator. The for is part of the list comprehension itself.

The ternary operator is written in boldface here. In the C/C++/C#/Java, we would have written it as:

// Java equivalent
emoticon_re.search(token) ? token : token.lower()

So basically for every item in the list, it will apply the ternary operator. The list comprehension is equivalent to:

# list comprehension is equivalent to:
tmp = []
for token in tokens:
    if emoticon_re.search(token):
        tmp.append(token)
    else:
        tmp.append(token.lower())
tokens = tmp
Sign up to request clarification or add additional context in comments.

Comments

3

Formatted comment:

tokens = [token if emoticon_re.search(token) else token.lower() for token in tokens]

is equivalent to

tokens = [(token if emoticon_re.search(token) else token.lower()) for token in tokens]

6 Comments

Can we write this without for loop, i.e. just using an if condition to put a single default value in the list?. I'm getting syntax errors this way.
@y_159 I don't understand what you mean. The whole point of a list comprehension is to loop over something to build a list. There are two syntax elements combined here: a list comprehension ([foo for bar in baz]) and a conditional expression (foo if bar else baz). If you just need a single value in a list depending on a condition, you can do [foo if bar else baz]. If bar is truthy, you'll get [foo], otherwise you'll get [baz]. Does this answer your question?
yes it does. but can we omit else here. I was getting syntax error in that case. instead of baz i wanted an empty list. My question got answered here stackoverflow.com/questions/72681789
@y_159 I see. Yes, the conditional expression must have an else part. You got some pretty terrible answers there; ignore the list comprehension suggestions. Go for ['True'] if condition else []. Or perhaps even better: result = []; of condition: result.append('True').
yes i followed the first one only, seems more pythonic and reasonable way to go with. btw result = []; of condition: result.append('True') expression got some c/c++ style syntax.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.