for and if in one line

A forum for general discussion of the Python programming language.

for and if in one line

Postby johann99 » Thu Sep 19, 2013 6:59 pm

I'm trying to achieve a for-if-statement in one line:
I have a zipped list of lists and want to iterate through the entries and check for something.

def some_function(Q_chosen, Number_chosen, Energy_chosen, info_field_calc):
for Q_out, fieldreal_out, Number_out, Energy_out, Vebit_out in info_field_calc:
if Q_out == Q_chosen and Number_out == Number_chosen and Energy_out == Energy_chosen:
listfields = fieldreal_out
return listfields

I want to get the for and if statement in one line using the data types that I'm already using now. Is that possible?
Thanks a lot in advance!

Posts: 6
Joined: Fri Aug 16, 2013 2:05 am

Re: for and if in one line

Postby metulburr » Thu Sep 19, 2013 7:37 pm

for and if in one line

you would use a list comp:
Code: Select all
l = [x for x in [1,2,3,4] if x%2==0]
we will be moving to on October 1 2016
more details here
User avatar
Posts: 2244
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: for and if in one line

Postby ochichinyezaboombwa » Thu Sep 19, 2013 7:40 pm

1) read this, especially regarding code tags.
2) you can mix for and if in a single line easily, e.g.:
Code: Select all
[(x*18,y) for (x,y) in zip(range(5), range(10,60,10)) if x % 2 == 0]

but it's hard from your post to understand what exactly you want and especially why do you need to put if and for in a single line.
What does your function return if the inner condition is never satisfied?

OOPS: metulburr beat me on this one:-).
Posts: 203
Joined: Tue Jun 04, 2013 7:53 pm

Return to General Discussions

Who is online

Users browsing this forum: No registered users and 5 guests