Home > Blockchain >  Define sum for elements of multiple list with [] elements in Python
Define sum for elements of multiple list with [] elements in Python

Time:04-24

world! I have the problem with removing elements from multiple list. I have multiple list like this:

[['4:10'], ['3:20'], ['3:45'], ['Delete me'], ['5:00']]

So, when I found and deleted the element 'Delete me' via method pop, I had a list:

[['4:10'], ['3:20'], ['3:45'], [], ['5:00']]

So, when I trying to access list[3][0] it has wrote me "list index out of range". So I decided that the element was removed.

But anyway I couldn't to define the sum of all my elements. I still continue get the message

IndexError: list index out of range

Help me please how can I solve the problem?

CodePudding user response:

There are many ways you can handle it!

Enumerate

l = [['4:10'], ['3:20'], ['3:45'], ['Delete me'], ['5:00'], ['Delete me'], ['10:00']]

for i,e in enumerate(l):
    if e == ["Delete me"]:
        l.pop(i)

print(l) #[['4:10'], ['3:20'], ['3:45'], ['5:00'], ['10:00']]

But if you don't really know how to use enumerate:

Try/Except

l = [['4:10'], ['3:20'], ['3:45'], ['Delete me'], ['5:00'], ['Delete me'], ['10:00']]

for i in range(len(l)):
    try:
        if l[i] == ["Delete me"]:
            l.pop(i)
    except IndexError:
        pass

print(l) #[['4:10'], ['3:20'], ['3:45'], ['5:00'], ['10:00']]

To make it easy: When there is an "IndexError" the program just pass as nothing happened. (In reality, it's more complex from the system point of view but you can interpret it like that!)

Remove

l = [['4:10'], ['3:20'], ['3:45'], ['Delete me'], ['5:00'], ['Delete me'], ['10:00']]

for e in l:
    if e == ["Delete me"]:
        l.remove(e)

print(l) #[['4:10'], ['3:20'], ['3:45'], ['5:00'], ['10:00']]

Last but not least! list.remove(element) remove the element from the list and not the element by an index like pop

CodePudding user response:

I think to want to remove the non numeric data from the list and then go to that sum which you are referring, so it could be done by code snippet below:

n_list = [['4:10'], ['3:20'], ['3:45'], ['Delete me'], ['5:00'], ['Delete me'], ['10:00']]

for each in n_list:
if !(each[0].isnumeric()):
   n_list.remove(each)
print(n_list) #[['4:10'], ['3:20'], ['3:45'], ['5:00'], ['10:00']]

By this you can get only numeric data in your list.

  • Related