List comprehension with multiple conditions and value reassignment

python list comprehension multiple conditions
python list comprehension multiple variables
nested list comprehension python
python list comprehension two lists
python list comprehension if
python list comprehension multiple values
list comprehension python for loop
list comprehension python3

I have a function that has several conditions (5 exactly) that model this statement:

for n, i in enumerate(EPS_List_EPSV):
        if i == 'Very Satisfied':
            EPS_List_EPSV[n] = 1
        elif i == 'Satisfied':
            EPS_List_EPSV[n] = 2
        elif i == 'Dissatisfied':
            EPS_List_EPSV[n] = 3
        else:
            EPS_List_EPSV[n] = 4

I was wondering if there is a more pythonic way of writing this, due to the function's length being absurdly long. I understand list comprehension in dealing with one variable but is there a way to write this using list comprehension? Writing it correctly is evading me.

Using a dictionary and a list comprehension:

corr = {"Very Satisfied":1, "Satisfied":2, "Dissatisfied":3}
EPS_List_EPSV = [corr.get(el, 4) for el in EPS_List_EPSV]

For example:

EPS_List_EPSV = ["Very Satisfied", "Satisfied", "Satisfied", "Dissatisfied", "Other"]

with the use of the above code becomes: [1, 2, 2, 3, 4]

When to Use a List Comprehension in Python – Real Python, Python list comprehensions make it easy to create lists while performing However, many developers struggle to fully leverage the more they allow list comprehensions to filter out unwanted values, which would Python 3.8 will introduce the assignment expression, also known as the walrus operator. This syntax isn't related to list comprehensions. If you want to conditionally include one thing or a different thing in a list comprehension, this is what you would use: var_even = [x if x%2==0 else 'odd' for x in var] # ^ "if" over here for "this or that" A list comprehension filter clause is the if thing in elem for x in y if thing.

Use dict:

d = {
    'Very Satisfied': 1,
    'Satisfied': 2,
    'Dissatisfied': 3    
}

EPS_List_EPSV = ['Very Satisfied', 'Something Else', 'Satisfied', 'Something Else', 'Dissatisfied'

for n, i in enumerate(EPS_List_EPSV):
    EPS_List_EPSV[n] = d.get(i, 4)

print(EPS_List_EPSV)
[1, 4, 2, 4, 3]

d.get is to return 4 if any undefined key is given.

Can multiple lists be assigned values in just one list comprehension , to assign values to multiple lists using one line of code or using a list of “too many values to unpack” when you try to do it in a list comprehension? and thought I could combine multiple variable assignment with lists too. Remember, this is a nested conditional, not an AND operation of two conditions. b. if..else in List Comprehension in Python. You can also use an if-else in a list comprehension in Python. Since in a comprehension, the first thing we specify is the value to put in a list, this is where we put our if-else.

If I were I would create a dict

dictio = {'Very Satisfied' : 1, 'Satisfied': 2, 'Dissatisfied' : 3, 'other' : 4}

Then your code shoud look like :

for n, i in enumerate(EPS_List_EPSV):
    EPS_List_EPSV = dictio[i]

Edit : Chris answer is more accurate since it does not raise KeyError in case the ESP_List_EPSV contains a word that is not in the dict

Python List Comprehension with Multiple Conditions, Python List Comprehension – Multiple IF Conditions. Python List Comprehension is used to create Lists. While generating elements of this list, you can provide� List comprehensions can be rewritten as for loops, though not every for loop is able to be rewritten as a list comprehension. Using our list comprehension that created the shark_letters list above, let’s rewrite it as a for loop. This may help us better understand how the list comprehension works.

PEP 572 -- Assignment Expressions, Simplifying list comprehensions; Capturing condition values; Fork During the development of this PEP many people (supporters and critics� Multiple If Conditions. Now that you have understood how you can add conditions, it's time to convert the following for loop to a list comprehension with conditionals. divided = [] for x in range(100): if x%2 == 0 : if x%6 == 0: divided.append(x) Be careful, you see that the following for loop contains two conditions!

10.22. List Comprehensions — How to Think like a Computer , List Comprehensions�. The previous example creates a list from a sequence of values based on some selection criteria. An easy way to do this type of� Here, square brackets signify that the output is a list.n**2 is the expression executed for each element and for n in numbers is used to iterate over each element. In other words, execute n**2

Python, By using list comprehension one can achieve this task with ease and in one line. We run a loop for specific indices in RHS and assign them to the required� Using list comprehension in functions. Now, let’s see how we can use list comprehension in functions. # Create a function and name it double: def double(x): return x*2 # If you now just print that function with a value in it, it should look like this: >>> print double(10) 20 We can easily use list comprehension on that function.

Comments
  • we have dict.get method for this kind of things
  • corr[el] if el in corr.keys() else 4 is corr.get(el, 4).
  • Thanks, it makes more sense to use it in fact. Edited.