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

Time:01-20

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]]?

CodePudding user response:

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

CodePudding user response:

In code that should be:

[[None if i==1 else v for i,v in enumerate(l)] for l in [[1,2,3], [4,5,6]]]

This of course creates a new list

CodePudding user response:

l=[[1,2,3],[4,5,6]]
[[a, None, c] for a,b,c in l]
#[[1, None, 2], [4, None, 5]]

CodePudding user response:

If you want to change the original list in-place:

l = [[1, 2, 3], [4, 5, 6]]
for sub in l:
    sub[1] = None
print(l)
# [[1, None, 3], [4, None, 6]]

CodePudding user response:

If you want to use nested list comprehension structure

[[k[i] if i != 1 else None for i in range(len(k))] for k in [[1,2,3],[4,5,6]]]
# [[1, None, 3], [4, None, 6]]
  • Related