Search code examples
pythonpython-3.xlistlist-comprehension

How to change the element at a specific index for all sub-lists?


I have a list like this: [[1, 2, 3], [4, 5, 6]]

I want to change it to [[1, None, 3], [4, None, 6]] using list comprehension.

I have tried:

print(list(x[1] = None for x in [[1, 2, 3], [4, 5, 6]]))

Which throws the error SyntaxError: expression cannot contain assignment, perhaps you meant "==".

I also tried:

print(list(x1 for x in [[1, 2, 3], [4, 5, 6]] for x1 in x))

but this just gives [1, 2, 3, 4, 5, 6].

I have been thinking for like 1 hour, anyone know how to change my code output to [[1, None, 3], [4, None, 6]]?


Solution

  • The data shown in the question is a list comprised of 2 sub-lists each of 3 elements.

    Let's assume that it's the second value in each sub-list that should be substituted with None and that the sub-lists might vary in length. In that case:

    _list = [[1,2,3],[4,5,6]]
    
    new_list = [[x, None, *y] for x, _, *y in _list]
    
    print(new_list)
    

    Output:

    [[1, None, 3], [4, None, 6]]
    

    Now let's change the data to:

    _list = [[1, 2, 3], [4, 5, 6, 7]]
    

    ...then the same list comprehension would generate:

    [[1, None, 3], [4, None, 6, 7]]
    

    Note:

    This will fail if any sub-list contains fewer than 2 elements