How do the variables in a `for` statement get defined? [duplicate] - python

This question already has answers here:
Python Variable Declaration
(6 answers)
Understanding for loops in Python
(4 answers)
Closed 4 years ago.
I came across code like this:
s1 = "mit u rock"
s2 = "i rule mit"
if len(s1) == len(s2):
for char1 in s1:
for char2 in s2:
if char1 == char2:
print("common letter")
break
I notice there are no previous defines for the variable like char1 or char2, so how does this work? I think it might be some "keyword for a variable" that Python understands. If so, could you tell me what's it called, and what are other common variables like this?

What that for loop does is loop over s1. For every iteration it assigns an element of iterable container s1 to variable char1.
Therefore, on the first iteration of the loop for char1 in s1, char1 will have the string value 'm', on the second iteration string value 'i'.
Note that even after the loop has finished executing, char1 will still have a value assigned (the last iteration means it will have value 'k').
What your iterating over doesn't have to be a string, it can be any object that defines __iter__ and __next__ methods. So some examples are a list [1,2,3] or a generator like what is returned by function invokation range(5).

Related

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))

Is a dynamic expression as collection in a list comprenhension evaluated only once? [duplicate]

This question already has an answer here:
How many times does a for loop evaluate its expression list?
(1 answer)
Closed 1 year ago.
Is a dynamic expression as collection in a list comprenhension evaluated only once? For example:
val_str = [str(val) for val in list(range(10))]
Is the list(range(10)) bit evaluated only once or 10 times?
Short answer: It is only evaluated once
Now let's prove it. We'll create a function with a print inside it and see how many times it's printing:
def my_range(stop):
print("my_range called")
return range(stop)
val_str = [str(val) for val in list(my_range(10))]
The output contains only one line eargo my_range is only called once.

Can someone tell me the difference between the following two methods for traversing and modifying a list in Python3? [duplicate]

This question already has answers here:
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 2 years ago.
The given problem -
Given a string, return a string where for every character in the original there are three characters
paper_doll('Hello') --> 'HHHeeellllllooo'
If I do this, I get the correct answer -
def paper_doll(text):
s1 = list(text)
for i in range(0,len(s1)):
s1[i] = s1[i]*3
s2 = "".join(s1)
return s2
# Check
paper_doll('Hello')
'HHHeeellllllooo'
But this doesn't work -
def paper_doll(text):
s1 = list(text)
for i in s1:
i= i*3
s2 = "".join(s1)
return s2
#Check
paper_doll('Hello')
'Hello'
Isn't i in the latter same as s1[i] in the former? What am I missing here?
You second version : i= i*3 just replaces the value assigned to the label(variable) i. i=H*3 which means HHH but does not replace the item inside the list as the first part of code does.
The context in first example is replacing the item inside the list.

How to check if a value is NOT a list [duplicate]

This question already has answers here:
What's the canonical way to check for type in Python?
(15 answers)
Closed 3 years ago.
I need to check if a value is a list before carrying out the rest of the code. The for loop should only be run if my_list is a list.
sum=0
if not list:
print("The input is not a list or is empty.")
exit()
for item in (list):
sum+=1
print("The length of the list is ",sum)
my_list = "Hello";
list_length(my_list)
The code works as expected when my_list is an actual list, but if I set it equal to a string, "Hello" at the moment in my code, the output is 5, I want it to not have an output.
you can use
if isinstance([], list):
print("this is list")
to check.
and if you want to check is subclass, you can use
if issubclass(sub_class, your_class):
print(f"this is subclass of {your_class}")

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

Categories

Resources