The problem seems very easy, but unfortunately I can't solve it.
Let list
A = [[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15]]
I want to create a new list by removing list [7,8,9]
The remove is not creating a new list: A.remove(2)
And set(A) - set([7,8,9])
throwing the following error.
TypeError: unhashable type: 'list'
Can someone please help me to solve the issue?
CodePudding user response:
If you absolutely needs to remove based on indice and not value, it may be done with a list comprehension:
A = [value for i,value in enumerate(A) if i != 2]
CodePudding user response:
A.remove() removes a element from a list, not index. you can use del a[2] instead
To create a new list i usally do:
import copy
newlist = deepcopy.copy(a)
newlist.remove([7,8,9])
Problem is a list is a pointer so therefor when creating
b = a
you simply just make a new pointer and not a new list. So by deepcopying you create a new address in memory
CodePudding user response:
A = [[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15]]
A1 = A.copy()
A1.remove([7,8,9])
A1
# [[1, 2, 3], [4, 5, 6], [10, 11, 12], [13, 14, 15]]
use it like this
CodePudding user response:
A simple solution:
A = [[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15]]
# When B contain only 1 list
B = [7,8,9]
C = [n for n in A if n != B]
# When B contains more than 1 lists
B = [[7,8,9]]
C = [n for n in A if n not in B]
# C = [[1, 2, 3], [4, 5, 6], [10, 11, 12], [13, 14, 15]]
CodePudding user response:
remove desired using remove function and assign it to another variable newList = A.remove([7,8,9])