Search code examples
pythonif-statementlist-comprehension

Condition in python lists comprehensions


friends-coders! Help with condition in lists comprehensions at python code, please. Where are mistake in that syntax?

matrix = [
  [matrix[i][j] = '.' if matrix[i][j] % 2 == 0 else matrix[i][j] = '*' for i in range(int(col))] 
  for j in range(int(row))
] 

Don’t know how to resolve this problem.


Solution

  • Although you didn't provide a description of the desired result, it's likely that you were after this:

    matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    col = 3
    row = 3
    
    matrix = [
      ['.' if matrix[i][j] % 2 == 0 else '*' for i in range(int(col))]
      for j in range(int(row))
    ]
    
    print(matrix)
    

    Output:

    [['*', '.', '*'], ['.', '*', '.'], ['*', '.', '*']]
    

    It generates a new matrix with a '.' in place of every even value and a '*' in place of every odd one, and assigns the result to matrix, overwriting the original data.

    A few remarks on the code you shared:

    • You were assigning a newly created list to matrix, but also had assignment statements (i.e. [matrix[i][j] =) in the list comprehension, which does not work.
    • You have int(col) and int(row) suggesting that these were not int values to begin with; in my example they are, but since you provided no code defining them, some guesswork is required and I left them in. I assumed they represented the size of the nested list matrix.

    As user @Chris indicates in the comments, a more concise solution to your problem would be:

    matrix = [['.' if x % 2 == 0 else '*' for x in row] for row in matrix]
    

    This avoids the use of indices altogether and will also work for nested lists that don't form a rectangular matrix.