6

I was wondering how would you can replace values of a list using list comprehension. e.g.

theList = [[1,2,3],[4,5,6],[7,8,9]]
newList = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(theList)):
  for j in range(len(theList)):
    if theList[i][j] % 2 == 0:
      newList[i][j] = 'hey'

I want to know how I could convert this into the list comprehension format.

3
  • 6
    List comprehension is always going to create a new list. Not replace values in an existing one. Commented Feb 15, 2018 at 3:53
  • 1
    Can you paste expected output? Commented Feb 15, 2018 at 3:59
  • 1
    [[1,hey,3],[hey,5,hey],[7,hey,y]] Commented Feb 15, 2018 at 4:03

3 Answers 3

6

You can just do a nested list comprehension:

theList = [[1,2,3],[4,5,6],[7,8,9]]
[[x if x % 2 else 'hey' for x in sl] for sl in theList]

returns

[[1, 'hey', 3], ['hey', 5, 'hey'], [7, 'hey', 9]]
Sign up to request clarification or add additional context in comments.

Comments

1

Code:

new_list2 = [["hey" if x %2 == 0 else x for x in row]
             for row in theList]

Test Code:

theList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
newList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in range(len(theList)):
    for j in range(len(theList)):
        if theList[i][j] % 2 == 0:
            newList[i][j] = "hey'ere"


new_list2 = [["hey'ere" if x %2 == 0 else x for x in row]
             for row in theList]

assert newList == new_list2

Or...

Or if you are literally replacing items in newList based on values in theList you can do:

newList = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
newList[:] = [["hey" if x % 2 == 0 else y for x, y in zip(row1, row2)]
              for row1, row2 in zip(theList, newList)]

print(newList)

Results:

[[10, 'hey', 30], ['hey', 50, 'hey'], [70, 'hey', 90]]

1 Comment

Technically, this isn't equivalent to the OP's example. For instance, this does not work if newList is initially different from theList.
0
def f(a, b):
    print(a, b)
    return 'hey' if a % 2 == 0 else b

newList = [[f(a, b) for a, b in zip(r1, r2)] for r1, r2 in zip(theList, newList)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.