Nibaga Nibaga - 21 days ago 6
Python Question

How to remove one item in this list?

Suppose I have 2 lists

list1 = [['abc', '123'], ['def', '456']]
list2 = ['abc','123','def','456','ghi','789']


How can I remove 1 element from list1 by typing only the letters or the number

For example if I type 'abc' OR '123' I want it to display

[['def', '456'], ['ghi', '789']]


in list2 I can make it remove the pair by the following code

contact = input("Type the name/number of the contact you want to remove")
if contact in list2:
pos = list2.index(contato)
if pos % 2 == 0:
list2.pop(pos)
list2.pop(pos)
if pos % 2 != 0:
list2.pop(pos-1)
list2.pop(pos-1)


However I wouldn't be able to do that in list1 as both number and letters are together so the I guess the only way would be to transfer the new list2 to list1 but I'm not sure how I would do that

I know what I wrote is really confusing, but basically I want to transform

this: ['def','456','ghi','789'] into this: [['def', '456'], ['ghi', '789']]

Answer

I know what I wrote is really confusing, but basically I want to transform

this: ['def','456','ghi','789'] into this: [['def', '456'], ['ghi', '789']]

Use a simple list comprehension to nest the list at every two elements:

>>> l = ['def','456','ghi','789']
>>> l = [[i, j] for i, j in zip(l[0::2], l[1::2])]
>>> l
[['def', '456'], ['ghi', '789']]
>>> 

What this does is it iterates through the list by every two elements. This only works however if the list are the same length. This would break:

>>> l = ['def','456','ghi','789', 'foo']
>>> l = [[i, j] for i, j in zip(l[0::2], l[1::2])]
>>> l
[['def', '456'], ['ghi', '789']]
>>> 

The problem, is the builtin zip() stops at the shortest iterable. If you need to group a list that can have uneven length, use itertools.zip_longest(). It will fill None into any unmatched values:

>>> from itertools import zip_longest # izip_longest for Python 2.x users
>>> l = ['def','456','ghi','789', 'foo']
>>> l = [[i, j] for i, j in zip_longest(l[0::2], l[1::2])]
>>> l
[['def', '456'], ['ghi', '789'], ['foo', None]]
>>>