0

in python am having a list of list as shown below:

list1 = [['BF001', '26-OCT-2020', '6167', '1', '07:35'],\   
 ['Summary', '26-OCT-2020', '', '', '', ''],\   
 ['BF004', '26-OCT-2020', '327', '2', '08:25'],\  
 ['Summary', '26-OCT-2020', '', '', '', '' ],\  
 ['BF005', '26-OCT-2020', '26983', '3', '07:40'],\  
['BF005', '26-OCT-2020', '26983', '3', '07:40'],\  
['BF005', '26-OCT-2020', '26983', '3', '07:40']]   

i need to remove the sublist whose first element is 'Summary'. i have tried the following code:

for i in range(len(list1)):  
  if list1[i][0]=='Summary':  
    list1.pop[i]

but i am getting index out of range error.

0

5 Answers 5

2

you are modifying a list while you are iterating over it. that will not work as expected.

what you could do is use a list-comprehension:

lst = [item for item in list1 if item[0] != 'Summary']

you could also mutate your current list directly:

list1[:] = [item for item in list1 if item[0] != 'Summary']
Sign up to request clarification or add additional context in comments.

Comments

0

You'd better use a new list:

new_list2 = []
for i in range(len(list1)):
  if list1[i][0] != 'Summary':
    new_list2.append(list1[i])

or, with list-comprehension:

new_list2 = [l for l in list1 if l[0] != 'Summary']

Comments

0

After each pop the length of your list changes. So the second pop will have a shorter list and eventually the argument to pop might be to big for the remaining list.

If you need in place modification, you can iterate the list in reverse to prevent this problem:

for i in range(len(list1)-1, -1, -1):
    if list1[i][0] == 'Summary':
        list1.pop(i)

Comments

0

You can even modify list while iterating over the list with comprehension:

list1 = [x for x in list1 if not x[0] == 'Summary']

Comments

0

You can iterate over the items directly and pop via the index method like so:

for l in list1:
    if l[0] == 'Summary':
        list1.pop(list1.index(l))

However, this will not work if there's more than one summary. As others mentioned, this is because the index changes when you pop an item.

Therefore, the best way is to use a list comprehension and create a new list of all the items that aren't the summary. It can even have the same variable name:

list1 = [item for item in list1 if item[0] != 'Summary']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.