This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 6 years ago.
I'm trying to delete binary numbers from a list that don't contain the number of zeroes a user enters.
a = []
for i in range(512):
a.append(format(i, '09b'))
b = int(input("Enter zeroes: "))
for i in a:
if i.count('0') != b:
del(i)
for i in a:
print(i)
But running this code still yields the full list of 9 bit numbers. Where am I going wrong?
You need to use a.pop in order to delete something from the list.
However, you'd be much better off simply recreating the list, like this:
new_a = [i for i in a if i.count('0') == b]
It's more functional, and more clearly expresses what you're trying to do. It's also possibly more efficient. Deleting items randomly from a list is a linear operation. If you do it n times, you might end up with a quadratic algorithm. Rebuilding the list is only linear.
Related
This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
How to remove items from a list while iterating?
(25 answers)
Closed 12 months ago.
I was trying to sort a list using for loops in python.
I wrote the code like this.
L=[1,2,3,6,7,9,4]
NL=[]
for i in L:
NL.append(min(L))
L.remove(min(L))
print(NL)
But here the output is [1, 2, 3, 4].
I can't understand why the output is stopping at 4. I am new to coding. It would be helpful if someone could help me with this.
You're removing elements from a list while looping over it, which is problematic (if the index of the element you're removing is before your current loop index, the "next element" being shifted back by one won't be visited). As you don't need to work with the index anyways, you can simply loop n times, where n is the number of elements in the list (the length of the list):
L=[1,2,3,6,7,9,4]
NL=[]
for _ in range(len(L)):
NL.append(min(L))
L.remove(min(L))
print(NL)
Side note: The algorithm you've implemented is called "selectionsort" and has quadratic time complexity. You're also emptying the input list. In practice, you should usually be using Python's builtin [...].sort() to sort the input list in place; if you want a sorted copy, you can always call [...].copy() first.
This question already has answers here:
Divide elements of a list by integer with list comprehension: index out of range
(5 answers)
Closed 3 years ago.
I have a list of numbers and i need to divide them all by a specific number.
Lets say i want to divide all of the items by 2
list = [1,2,3,4,5,6,7]
wanted_list = [1/2,2/2,3/2,4/2,5/2,6/2,7/2]
I attempted a for loop that changes each but it didnt work for some reason like it didnt do the operation.
list = [1,2,3,4,5,6,7]
wanted_list = [i/2 for i in list]
print(wanted_list)
I assume san's answer is the best approach, as it utilizes lists comprehension and in that case a new list is created automatically, however considering what you wrote, you can as well use a for loop, only you need to store the result somewhere, ex:
data = [2, 4, 6]
wanted_data = []
for d in data:
wanted_data.append(int(d/2))
print(wanted_data)
This question already has answers here:
split list into 2 lists corresponding to every other element [duplicate]
(3 answers)
Closed 4 years ago.
Say i have this list:
CP = [1,0,1,0]
How can i print only 0's in the list via indices i.e CP[i].
Required output:
0
0
Any help would be highly appreciated!
This feels like a homework problem, and I assume you actually want odd indices instead of even indices.
Here's a possible solution:
# get a range of all odd numbers between 1 and length of list
# with a step size of 2
for i in range(1, len(CP), 2):
print(CP[i])
The one liner --
print ('\n'.join([str(CP[i]) for i in range(1, len(CP), 2)]))
This question already has answers here:
Selecting a random list element of length n in Python
(4 answers)
How do you pick "x" number of unique numbers from a list in Python?
(7 answers)
Closed 5 years ago.
Let's say i have a list. I want to iterate over that list and add 2 random strings from it to an empty list. However, because this is a random choice, there is a possibility that the same string will be picked twice (As it is crucial not to pop or delete from that list the selected item). something like this:
import random
emptylist = []
somelist = ["a","b","c","d","e",]
for item in somelist:
emptylist.append(random.choice(somelist))
emptylist.append(random.choice(somelist))
How do i make sure that it won't pick, for example, "a" twice?
I know it is possible in many ways but im looking for the most efficient one.
This question already has answers here:
How to sort python list of strings of numbers
(4 answers)
Closed 8 years ago.
I am using the following function in order to sort a list in an increasing order. However, while my function works for lists such as: [1,5,6,9,3] or [56,43,16,97,45], it does not work for lists of the form: [20,10,1,3,50].
In such cases, the computer seems to consider that 3>20 and 3>10 and 3 ends up right before 50 (second to last) in the "sorted" list I get. More precisely the result I get is: [1,10,20,3,50].
Here is my code:
def function_sort(L):
for j in range(len(L)):
min=j
for i in range(j+1,len(L)):
if L[i]<L[min]:
min = i
if(min != j):
L[j],L[min] = L[min],L[j]
print L
return L
Could anyone please explain me what is going on?
It sounds like your list consists of strings rather than integers, and you end up getting the elements sorted lexicographically.
By way of illustration, consider the following:
>>> 10 < 2
False
>>> '10' < '2'
True
To fix the issue, convert the elements to integers before sorting:
L = map(int, L)
P.S. I recommend against using min as a variable name since it shadows the built-in function min().