user2208569
user2208569

Reputation: 109

Using list comprehension for a For/if/else loop

Essentially, I wrote a different set of code that called together a given shop's name and the total price of a grocery list if it was bought there.

As tuples use only the first element to compare (unless they are equal) I've set them up so that the total value is first.

It will loop through an index of the length of the myprices list and it will compare whether the current tuple is greater than the next tuple.

If it receives an index out of range error it will pass.

I use [0] and [1] locations within the individual tuples to denominate whether the program is accessing the price or the name of the shop.

It will compare the prices of the tuples (automatically) and then it will make bestprice = the name of the shop with the best price.

This is, essentially C programming being ported into python.

I've found pythonic ways to express single loops, but not if/else statements, and not the combination of both.

Do you have any suggestions for improvement here, or any paradigms I'm embracing that can be replaced in python.

myprices = [(6, shop1), (10, shop2)]
bestprice = []
for i in range(len(myprices)):
    try:
        if myprices[i] < myprices[i+1]:
            bestprice = myprice[i][1]
        else:
            bestprice = myprices [i+1][1]
    except IndexError:
        pass

Upvotes: 0

Views: 389

Answers (2)

John Y
John Y

Reputation: 14529

The idiomatic way to find the maximum value of a collection in Python is the max built-in function:

bestprice = max(myprices)[1]  # index of 1 to get the shop name

Your example really has no use for loops or comprehensions. I don't see why you pre-assign bestprice to be an empty list when ultimately you want it to be a (single) string, not a list.

If you actually did want a list, then you can replace the following loop:

result = []
for elem in collection:
    if cond:
        result.append(myfunc(elem))

with the following list comprehension:

result = [myfunc(elem) for elem in collection if cond]

Upvotes: 5

Daniel Roseman
Daniel Roseman

Reputation: 599610

That's really not how you would do it in C, and it shouldn't be how you do it in Python either. In any language, there are a couple of ways to do this; either you keep a variable tracking the highest so far and update it whenever you see one that's higher:

highestr = (0,)
for item in myprices:
    if item[0] > highest_so_far[0]:
        highest = item

Or you simply sort descending and take the first one:

myprices.sort(reverse=True)
highest = myprices[0]

Upvotes: 1

Related Questions