Variable in while loop not incrementing after for loops [duplicate] - python

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.

Related

Is there a way to manipulate the counter in a "for" loop in python [duplicate]

This question already has answers here:
How to change index of a for loop?
(5 answers)
Closed last year.
By "counter" I mean the "i" in the code I attached. I just picked up Python for University, and I was wondering if i could maniuplate the counter just like you can in C++
n=5
for i in range(n):
print("Test")
i=i-1
The result of this code is
Test
Test
Test
Test
Test
but i was wondering if you could manipulate the "i" so it is an infinite loop
Feel free to ask questions about what I mean if it is not clear enough
The problem is that python uses iterators, which aren't meant to be manipulated while getting iterated. A good rule is, if you need to manipulate a for loop, you shouldn't use a for loop. The better way would be, using a while loop. An example:
n = 10
while n > 5:
print("Test " + n)
n -= 2
if n == 6:
n += 1
Or the infinite loop:
while True:
print("Test")
Take a look at this for more information.

How to remove same value from one list and how to change ranges automatically [duplicate]

This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 1 year ago.
def my_list(enter_list):
#print(len(enter_list))--> 7 element
for i in range(0, len(enter_list)): # THE PROBLEM IS HERE
count = enter_list.count(enter_list[i])
if count >=2:
enter_list.pop(i)
return enter_list
print(my_list(["purple","coffee",2,6,2,"purple","steak"]))
At first there are 7 value in my list. But after I remove one of the same value from my list , my list's value is decreasing. İf I change the ranges range(0,len(enter_list)-2) like this. It works. I dont know how to change ranges automatically. ( I can change the ranges manually but it'll not work everytime. )
['coffee', 6, 2, 'purple', 'steak']
This is the output when I change the ranges manually.
Rather than attempt to modify the range you are iterating over, I would suggest you create a copy of the enter_list list and pop() the elements out of that list. That way you will be iterating over the full list of items, but you will return the modified version of the list without having to dynamically alter the range of your loop, which I don't believe is possible.
To quickly show the technique in your code:
def my_list(enter_list):
output_list = enter_list.copy()
for i in range(0, len(enter_list)):
count = enter_list.count(enter_list[i])
if count >=2:
output_list.pop(i)
return output_list
Here you return output_list, which will be your filtered version, but by copying the enter_list, you ensure you are iterating over the full set.
Just to add: using pop(i) here will likely result in you popping something out of range near the end of the loop, so this type of loop iterating over the elements might work best:
for items in enter_list:
output_list.pop(item)
Then you ensure you are not going to pop() on an out of range index.
You could do like this:
def my_list(lst):
i = 0
while True:
cnt = lst.count(lst[i])
if cnt > 1:
lst.pop(i)
i += 1
if len(lst) == i:
break
return lst
print(my_list(["purple","coffee",2,6,2,"purple","steak"]))
OUTPUT
['coffee', 6, 2, 'purple', 'steak']
The problem with your approach is that, in the for loop, the len of the list is only evaluated once - at the beginning. The reason why decreasing by 2 makes it work is because there are 2 elements which have one duplicate, so the loop does not go out of range.

Python nested loops, a little understanding needed [duplicate]

This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
return statement in for loops [duplicate]
(6 answers)
Closed 1 year ago.
Please see the below code
def common_letters(string_one,string_two):
letters_in_common = []
for letter in string_one:
for letter2 in string_two:
if letter == letter2:
letters_in_common.append(letter)
return letters_in_common
returned = common_letters("hello", "loha")
print(returned)
The above code works, but only on the first iteration of the outer loop, hence my letters_in_common list only returns ['h'] when it should return ['h','l','l'], In JS the syntax is different and the loop works incrementally.
Am I misunderstanding how loops work in Python or is there a syntax level step I have not included?
p.s. I am aware that I could use the 'in' keyword etc but I wanted to try it with a loop first.
Your return is indented so that it is inside if. Presumably you want to return after you check every letter against every letter, which means return has to be outside the loops:
def common_letters(string_one, string_two):
letters_in_common = []
for letter in string_one:
for letter2 in string_two:
if letter == letter2:
letters_in_common.append(letter)
return letters_in_common
Sidenote: This will give a somewhat surprising result if there are multiples of a shared letter in both strings. If I wanted to find out just the shared letters, I would use set intersection:
def common_letters(string_one, string_two):
return list(set(string_one) & set(string_two))

For loop iterating not executed with condition set inside [duplicate]

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'.

Repeat length of list on Python? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
find the maximum number in a list using a loop
I'm finding the maximum number in a list on Python by using a loop. In order to do that, I need to have a loop where it goes through the entire list. What loop can I use that runs through the entire list? I'm new to Python.
You can go through a list with a for loop like:
for item in lst:
# do something with item
However, an easier way to get the maximum item in a list (which appears to be what you want) is:
max(lst)
Repeating a block of code n times, where n is the length of some_list is done like this:
for i in xrange(len(some_list)):
# block of code
or...
i = 0
while i < len(some_list):
# block of code
i = i + 1
max = None
for e in lst:
if max is None or e > max: max = e
But as David already stated, simply calling max(lst) would do the job.

Categories

Resources