This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Closed 6 years ago.
I was reading through an article explaining list comprehensions and came across the following example which is supposed to build a list of non-prime numbers:
noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
I tried breaking the list comprehension down by running both for loops separately in a shell, but I'm still unclear as to the functionality of the statement. It seems that the first loop is supposed to be iterating through the list of numbers from 2 to 8 and then storing each number in j which is then passed to the second (nested?) loop which generates numbers from the current value of i times 2 until 50 in increments of i.
What I've described the actual functionality of the list comprehension?
This list comprehension performs the same as the following code:
noprimes = []
for i in range(2,8):
for j in range(i*2, 50, i):
noprimes.append(j)
Related
This question already has answers here:
Python list.remove() skips next element in list
(6 answers)
Closed 2 years ago.
I cannot figure why some numbers greater than 10 are still left. Please help.
Thanks.
mylist = [12,31,2,5,45,12,45,4,32,1,6,8,5,31,12,11]
for num in mylist:
if num >= 10:
mylist.remove(num)
print(mylist)
you are iterating a list that is being modified, so the iterator index skips to another thinking it's intact. I'd suggest another way for that goal
mylist = [number for number in mylist if number < 10]
This question already has answers here:
Appending to list with loop
(2 answers)
Closed 3 years ago.
I am trying to create a cartesian product of the alphabet with loops. I have for loops that create the desired output but i in my while loop is never reached for some reason.
This loop is running forever in a jupyter lab notebook.
lower_az = [chr(ord('a') + i) for i in range(26)]
i=0
n=2
lst = lower_az.copy()
final_list = []
while i < n:
for let in lst:
for j in range(26):
strng = let + lower_az[j]
lst.append(strng)
i += 1
final_list.append(lst)
Unless I am missing something obvious the variable i should increment until it reaches n and stop the while loop at the desired length of strings.
You are changing the list you are iterating over. The problem is not the while-loop, it's the lst.append(strng) while iterating for let in lst.
#blue_note is correct - Python doesn't behave well when you change a list you're iterating over.
It looks like this is just a typo, though: you've got final_list all ready to receive the elements. To fix this, change:
lst.append(strng)
to
final_list.append(strng)
and drop final_list.append(lst) and your program appears to work fine.
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 4 years ago.
I'm running the following code:
x = []
for i in c:
x = x+i
The result has about 50-100 million elements.
This takes several minutes to run on my PC. How can I accelerate this?
Already compared in join list of lists in python
with Python 2 being faster with .extend than with itertools.chain
An exotique method
l = []
for x in c: l[0:0] = x
among the faster according to
stackoverflow.com/questions/12088089/…
For python 3.5 and latter, even more exotic
l = []
for x in c:
l = [l, *x]
Of course sum(c, []) is among worst on all the measurements.
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 5 years ago.
Trying to remove negative numbers from a list. I kept running into an issue where two successive negative numbers did not get removed. My code is quite simple:
numbers = [-5, 1, -3, -1]
def remove_neg(num_list):
for item in num_list:
if item < 0:
num_list.remove(item)
print(remove_neg(numbers))
#[1, -1]
I found the answer online after trying 4 different versions of my code and pulling a few hairs out of my head. The answer I found assigned r = numbers[:] and then removed items from r instead of the initial list.
def remove_neg(num_list):
r = numbers [:]
for item in num_list:
if item < 0:
r.remove(item)
print(r)
I understand this concept to have two list variables point to separate data. What I don't understand, is why my initial code doesn't work. Shouldn't for i in numbers: iterate through every item in the list? Why would two successive numbers not be treated the same? I've scoured looking for why and can't seem to find an answer.
In the first example you're modifying the list while iterating over it, which, as you've seen, messes up the iteration. While the second example works, it's very inefficient, and it would be much easier to use a list comprehension to construct a new list without the negatives:
def remove_neg(num_list):
return [x for x in num_list if x > 0]
This question already has answers here:
Python list problem [duplicate]
(2 answers)
Closed 5 years ago.
I have a simple python loop that iterate over a 2D list which has 1000 sublist inside. Each sublist will contain 3 string values. I only want to change the sublists which are after the 365th sublist. I also have a very trivial condition which will decide if an operation will be applied to the element. My minimum code is as follows:
def change_list(arr):
for i in range(len(arr)):
if i < 365:
pass
else:
arr[i][1] = str(int(arr[i][1]) * 2)
When apply this function in main I'll simply invoke this function as: change_list(parsed_lines). For parsed lines, I'll just give a simple example:
parsed_lines = [["afkj","12","234"]] * 1000
My function will do the "multiply by 2" operation on all sublists, which is an unexpected behavior. I've tried not using conditions, but results in the same behavior.
for i in range(365, len(arr)):
arr[i][1] = str(int(arr[i][1]) * 2)
Then I tried the other way to iterate my arr as:
for line in arr:
if arr.index(line) < 365:
print("I'm less than 365")
else:
line[1] = str(int(line[1]) * 2)
but this iteration will never execute the block under else. I am very confused by this, hope someone can help.
Update:
The expected behavior should be:
For arr[0: 365], the sublist will stay the same as: [["afkj","12","234"]]
For arr[365:], the sublist will be: [["afkj","24","234"]]
Your problem, as described, is not in the program, but in the test set. parsed_lines = [["afkj","12","234"]] * 1000 creates a list of 1000 references to the same list ["afkj","12","234"]. When it is modified through any of those references (say, above 365), it is seen as modified through any of those references (even below 365). In other words, parsed_lines[0][0]='foo' makes all fisrt elements in all sublists 'foo'.