If-else List of lists comprehension

Viewed 806

I have the following list of lists:

list1 = [[1,"one"],[2,"two"],[3,"three]]

I would like to have output of:

list2 = [[11,"one"],[2,"two"],[3,"three"]]

List comprehension with an if-else statement seems to be a good option for this.

list2 = [x if x[0] != 1 else 11 for x[0] in list1]

However, I get the NameError that 'x' is not defined. How should I define x?

3 Answers

You can not do for x[0] in <iterable>, you need to use the entire inner-list/sequence. To get the result you are looking for, you can either use second level list comprehension, or just the list concatenation with one level of comprehension as below:

>>> [x if x[0]!=1 else [11]+x[1:] for x in list1]
[[11, 'one'], [2, 'two'], [3, 'three']]

With a list comprehension, you have to rebuild the entire sublist, as there is no way to mutate a list and get the result with a single expression:

list2 = [x if x[0] != 1 else [x[0]+10, x[1]] for x in list1]

(Use *x instead of x[1] to generalize to longer sublists.)

With an ordinary for loop, you can simply mutate the existing list, if you don't need a shallow copy.

for x in list1:
    if x[0] == 1:
        x[0] += 10

(And in every case, you can replace addition by 10 with a hard-coded 11, since you know the exact value of x[0] if you condition succeeds.)

You need to make a couple of changes in code. I found the following issues:

  • You need to iterate over the entire list, hence you need the line: x in list1 instead of x[0] in list1
  • You need to add back both elements of the sublist, currently you directly added x without modifications

list2 = [[11, x[1]] if x[0] == 1 else x for x in list1]

Related