Understanding Python Ternary Operators Through Stock Symbol Evaluation

Use a ternary operator in a lambda function with apply to create new columns based on conditions, such as returning "standard" or "short" based on symbol length, or "buy" or "sell" based on stock price.

Learn how to use Python's ternary operator to write concise, readable conditional expressions, progressing from basic functions to lambda applications. This article walks through practical examples, including applying ternary logic to a pandas DataFrame for stock analysis.

Key Insights

  • Demonstrates how to convert a traditional if-else function into a one-liner using Python's ternary operator to classify stock symbols as "standard" or "short" based on string length.
  • Shows how to use lambda functions in conjunction with the ternary operator to apply conditional logic across pandas DataFrame columns, such as categorizing stock prices as "buy" or "sell."
  • Includes a hands-on example using a lambda function and apply() to create new DataFrame columns, reinforcing how this technique is used in data operations taught by Noble Desktop.

Note: These materials offer prospective students a preview of how our classes are structured. Students enrolled in this course will receive access to the full set of materials, including video lectures, project-based assignments, and instructor feedback.

If you're not used to ternaries, the ternary operator in Python, hopefully this will serve as a good gentle introduction or a refresher, depending on your experience with ternaries. So let's start out with a named function and start building this into lambdas. Given a stock symbol string, like cost for Costco or Palantir PLTR, one of these returns standard if it's more than three characters long and returns a string short if it's three characters or less.

All right, so get symbol length short of a symbol. We'll take in a symbol endpoint and we'll output one of those length strings, standard or short. If symbol, nope, we want to say if length of symbol is greater than three, I want to make it even more readable, greater than or equal to four, then return standard.

Else return short. And now we can test that function out. We can say get symbol length of ISRG.

And I've executed it. We get standard. What about Netflix? NFLX maybe? I believe so.

Standard. Now what about one like AstraZeneca, AZN? That should come out as short. There it is, short.

Python for Data Science Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

All right, so our function works. Now we could instead write it using a ternary. And this is how a ternary works.

We could say get symbol length is now a function where we take in a symbol and we'll set an answer variable to equal standard if length of symbol greater than or equal to four, else short. So this works very similar to our if, but our if really does a thing, returns a value, or prints something out, or makes a call to a database, whatever. An if and else usually does something.

A ternary, a one line ternary with an if and else in it is for if you want something to be a value. You want to set answer to equal a value. That's either standard if length of symbol is greater than or equal to four, or otherwise short.

And we get an actual value that way. And then here we got a return answer. All right, let's have our same, let's try our same tests.

Get symbol length of NFLX, and we'll get symbol length of AZN. Standard and short. Great, it works.

Now we could simplify this code if standard, if this evaluates to either standard or short, depending on the middle part, if length of symbol is greater than or equal to four, else, that instead of saving it into a variable and then returning it, we could instead just return it. But not the way I just did it. There we go.

Return this. So let's say return what the rest of this evaluates to. Standard if the symbol is greater than or equal to four length, otherwise short.

Let's run the function, run this cell. Yep, standard and short. Great.

So as you can imagine, this could for sure, let's put that comment up where we did it. We already did it. Skipping the intermediate variable and writing as one liner.

We could also, of course, rewrite it as a lambda function. We could say, get symbol length equals a lambda. It takes in S for symbol, maybe.

The sort of standard lambda style. And returns standard if the symbol, if length of the symbol is greater than or equal to four, else short. And these tests should still work.

Yep, they do. All right, so we've got this lambda function. We could use it by referring to get symbol length, or we could put the lambda directly in.

We're going to create a series of stock lengths from the symbol column. We'll say stocks at symbol dot apply. And again, we could call in, could do get symbol length.

We could also just do, typically we wouldn't have written any of that code above. And we'd say lambda symbol, maybe. Sometimes I like to do the longer version of variable name.

Lambda symbol, you return standard if symbol is greater than or equal to if length of symbol. I kept almost forgetting that. Now I have.

Okay. And we get back a series, a new column, like this. And we could, of course, say stocks at symbol length, maybe, equals this.

And then we can look at, okay, what stocks? Yep, it's got a symbol length, standard, or short. Okay. The next step is for you to try this on your own.

I want you to create a column called advice that contains buy if the stock price is under 200 and sell if it's at least 200. And you should use apply and a lambda function with a ternary. Let's see how you do.

I'll give you a moment. Feel free to pause the video here. How'd you do? Let's see one possible solution.

We could say stocks at advice equals stocks at price. Is that what it's called? Last price. Dot apply.

And we'll just pass in a lambda. We'll say, we'll call it each one price. And we'll return buy if price is greater than, no, less than 200.

You want to buy low and sell high. Else sell. Let's check stocks and see how we did.

Colin Jaffe

Colin Jaffe is a programmer, writer, and teacher with a passion for creative code, customizable computing environments, and simple puns. He loves teaching code, from the fundamentals of algorithmic thinking to the business logic and user flow of application building—he particularly enjoys teaching JavaScript, Python, API design, and front-end frameworks.

Colin has taught code to a diverse group of students since learning to code himself, including young men of color at All-Star Code, elementary school kids at The Coding Space, and marginalized groups at Pursuit. He also works as an instructor for Noble Desktop, where he teaches classes in the Full-Stack Web Development Certificate and the Data Science & AI Certificate.

Colin lives in Brooklyn with his wife, two kids, and many intricate board games.

More articles by Colin Jaffe

How to Learn Python

Master Python with hands-on training. Python is a popular object-oriented programming language used for data science, machine learning, and web development. 

Yelp Facebook LinkedIn YouTube Twitter Instagram