Python - x not in list error - python

I have a list inside a list and I am trying to remove any values in side the nested list that are equal to -1. I am getting a "ValueError: list.remove(x): x not in list" error when I try to run my code, any idea what I am doing wrong?
for x in list:
for i in x:
if i == -1:
list.remove(x)

You shouldn't mutate a list while iterating over it. You also shouldn't name a variable list, since that name is used by a built-in function. You can achieve what you want via a simple list comprehension:
my_list = [[x for x in v if x != -1] for v in my_list]

Related

Remove list for list

I receive a list in a list on this example:
y.append([x for x in range(0,6)])
The result:
[[0,1,2,3,4,5]]
How can I remove one []?
y.extend([x for x in range(0,6)])
or if you want to assign it to another value
a = [x for x in range(0,6)]
Just do this:
y.append([x for x in range(0,6)])
new_list = y[0]
new list will be the first list bit without one set of braces

How to compare and remove second element of a nested list using List comprehensions?

So I have a nested list and would like to compare and remove a list inside a nested list based on the condition match.
Here is my code :
def secondValue(val):
return val[1]
if __name__ == '__main__':
nestedList=[]
for _ in range(int(input())):
name = input()
score = float(input())
nestedList.append([name,score]) # Made a nested list from the input
lowestMarks=min(nestedList,key=secondValue) [1] #Extracting the minimum score
newList=[x for x in nestedList[1] if x!=lowestMarks] # PROBLEM HERE
The last line of my code is where I want to remove the list inside my nested list based on condition match. Sure, I can do this with a nested for loop but if there is a way to do this using list comprehension I'd consider that approach.
Basically I'd appreciate an answer that tells how to remove a list from a nested list based on a condition. In my case the list looks like :
[[test,23],[test2,44],......,[testn,23]]
Problems:
for x in nestedList[1] just iterates over second sublist of the nested list.
x is a sublist and it can never be equal to lowestMarks.
Use a list-comprehension as:
newList = [[x, y] for x, y in nestedList if y != lowestMarks]
Mistake was in the below line and is now fixed.
newList=[x for x in nestedList if x[1] != lowestMarks] # PROBLEM HERE
nestedList[1] fetches the second sub-list. You want to iterate over the entire list.

list index out of range while removing indexes from list

for y in range(len(List)):
print("length",len(List))
print ("y",y)
print("List",List[y])
if (List[y])%(dividing_prime)==0:
print(List[y])
counter=counter+1
List[y]=0
List.remove(0)
You are modifying a list while iterating over it. Because of that, the list is changing in size while you are iterating cause an index out of bounds.
What you could do is create another list from the elements you don't want to remove.
new_list = [x for x in mylist if not remove(x)]
If you want to keep the same list and not create a new copy then you could use the slice operator.
mylist[:] = [x for x in mylist if not remove(x)]
The itertools library also provides a tool to do this called filterfalse
https://docs.python.org/3/library/itertools.html#itertools.filterfalse

Extract substrings from a list into a list in Python

I have a Python list like:
['user#gmail.com', 'someone#hotmail.com'...]
And I want to extract only the strings after # into another list directly, such as:
mylist = ['gmail.com', 'hotmail.com'...]
Is it possible? split() doesn't seem to be working with lists.
This is my try:
for x in range(len(mylist)):
mylist[x].split("#",1)[1]
But it didn't give me a list of the output.
You're close, try these small tweaks:
Lists are iterables, which means its easier to use for-loops than you think:
for x in mylist:
#do something
Now, the thing you want to do is 1) split x at '#' and 2) add the result to another list.
#In order to add to another list you need to make another list
newlist = []
for x in mylist:
split_results = x.split('#')
# Now you have a tuple of the results of your split
# add the second item to the new list
newlist.append(split_results[1])
Once you understand that well, you can get fancy and use list comprehension:
newlist = [x.split('#')[1] for x in mylist]
That's my solution with nested for loops:
myl = ['user#gmail.com', 'someone#hotmail.com'...]
results = []
for element in myl:
for x in element:
if x == '#':
x = element.index('#')
results.append(element[x+1:])

What is an elegant way to convert the result of [x for x in y] from list to a regular variable?

What is an elegant way to convert the result of [x for x in y] from list to a regular variable?
result= [x for x in range(10) if x==7]
The result of the above will be [7].
I am now using result=result[0] but ...it does not look right :-)
thanks
You have a list comprehension on the right hand side. It evaluates to a list.
You want to pick up the first element (which is perhaps the only element for the kind of problems you are trying to solve) from it, so index the 0-th element in the list returned by the list comprehension, just like you would do it for a regular list.
result = [x for x in range(10) if x == 7][0]
You can also use a generator expression instead of a list expression and then call the next() function to retrieve the first item from the iterator returned by the generator expression.
result = next(x for x in range(10) if x == 7)
You can use next that retrieves the next object from the iterator. The parameter that goes within next is a generator. This allows saves you from fully constructing the list and then filtering for 7. Instead it only iterates until it hits 7, and wont evaluate until the next next(..) is called on the generator object.
>>> next(x for x in range(10) if x==7)
7

Categories