hbrovell
hbrovell

Reputation: 547

Delete second value in list thats in another list

I have a list that contains many other inner lists, and some of these inner lists contain two values. I want to delete all of the second values in the inner list.

[['a'], ['b'], ['c', 'd'], ['e'], ['f', 'g']]

Can I use rsplit() for this or are there any other split function that is better to use?

Upvotes: 1

Views: 99

Answers (4)

A. Colonna
A. Colonna

Reputation: 872

If you want to draw the element and drop them you can use the pop method :

list_list = [['a'], ['b'], ['c', 'd'], ['e'], ['f', 'g']
for my_list in list_list:
    if len(my_list) > 1:
        my_list.pop(1)

EDIT: Bad choice for my variable name

Upvotes: 1

skashyap
skashyap

Reputation: 143

Another way is using map functions

alist = [['a'], ['b'], ['c', 'd'], ['e'], ['f', 'g']]
reducedlist = list(map((lambda x: x[:1]), alist))
print(reducedlist)

This is creating a new list from the existing. Iterating over the list and deleting would be the best approach if you want to do it in-place

Upvotes: 1

lyxal
lyxal

Reputation: 1118

Another way of achieving your goal:

big_list = [['a'], ['b'], ['c', 'd'], ['e'], ['f', 'g']]
big_list = [sub_list[0] for sub_list in big_list]
print(my_list)

Output:
['a', 'b', 'c', 'e', 'f']

Or:

big_list = [['a'], ['b'], ['c', 'd'], ['e'], ['f', 'g']]
new_list = list()

for item in big_list:
    new_list.append(item[0])

print(new_list)

Output:
['a', 'b', 'c', 'e', 'f']

Upvotes: 0

L3viathan
L3viathan

Reputation: 27333

If you don't care about doing it in-place:

>>> outer = [['a'], ['b'], ['c', 'd'], ['e'], ['f', 'g']]
>>> outer = [inner[:1] for inner in outer]
>>> outer
[['a'], ['b'], ['c'], ['e'], ['f']]

I create a new list using a list comprehension, that contains slices of one element of the original inner lists.

If you need to do it in-place:

for inner in outer:
    if len(inner) > 1:
        del inner[1]

Upvotes: 6

Related Questions