Remove List from List of List and generate a new List

Question:

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?

Asked By: ragas

||

Answers:

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

Answered By: Sachin Kohli

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

Answered By: user1753626

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]]
Answered By: Timmy Lin

If you absolutely need to remove based on index and not value, it may be done with a list comprehension:

A = [value for i,value in enumerate(A) if i != 2]
Answered By: kzkb

remove desired using remove function and assign it to another variable
newList = A.remove([7,8,9])

Answered By: Paul
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.