What exactly is i in a for loop?
Python for-in loop preceded by a variable - Stack Overflow
Confused about for loops in Python. Please help me break down this code.
Can not understand for loops
Videos
I was working on a beginner's python exercise that involved writing a function that takes a list of floating numbers and returns the same list as strings displayed to 2 decimal places. This was what I initially wrote:
def formatted(a_list):
for i in a_list:
i = f"{i:.2f}"
return a_listprint(i) after i = f"{i:.2f}" showed correct values, but the returning a_list remained unedited. It seems to me that i does not represent the actual items within a_list, but behaves more so like a copied value?
I solved the problem by .append()-ing the formatted items to a new list but my lack of genuine understanding bugs me.
What's happening under the hood? What exactly is i in a for loop? Thanks!
The current answers are good, but do not talk about how they are just syntactic sugar to some pattern that we are so used to.
Let's start with an example, say we have 10 numbers, and we want a subset of those that are greater than, say, 5.
>>> numbers = [12, 34, 1, 4, 4, 67, 37, 9, 0, 81]
For the above task, the below approaches below are totally identical to one another, and go from most verbose to concise, readable and pythonic:
Approach 1
result = []
for index in range(len(numbers)):
if numbers[index] > 5:
result.append(numbers[index])
print result #Prints [12, 34, 67, 37, 9, 81]
Approach 2 (Slightly cleaner, for-in loops)
result = []
for number in numbers:
if number > 5:
result.append(number)
print result #Prints [12, 34, 67, 37, 9, 81]
Approach 3 (Enter List Comprehension)
result = [number for number in numbers if number > 5]
or more generally:
[function(number) for number in numbers if condition(number)]
where:
function(x)takes anxand transforms it into something useful (like for instance:x*x)- if
condition(x)returns any False-y value (False, None, empty string, empty list, etc ..) then the current iteration will be skipped (thinkcontinue). If the function return a non-False-y value then the current value makes it to the final resultant array (and goes through the transformation step above).
To understand the syntax in a slightly different manner, look at the Bonus section below.
For further information, follow the tutorial all other answers have linked: List Comprehension
Bonus
(Slightly un-pythonic, but putting it here for sake of completeness)
The example above can be written as:
result = filter(lambda x: x > 5, numbers)
The general expression above can be written as:
result = map(function, filter(condition, numbers)) #result is a list in Py2
It's a list comprehension
foo will be a filtered list of bar containing the objects with the attribute occupants > 1
bar can be a list, set, dict or any other iterable
Here is an example to clarify
>>> class Bar(object):
... def __init__(self, occupants):
... self.occupants = occupants
...
>>> bar=[Bar(0), Bar(1), Bar(2), Bar(3)]
>>> foo = [x for x in bar if x.occupants > 1]
>>> foo
[<__main__.Bar object at 0xb748516c>, <__main__.Bar object at 0xb748518c>]
So foo has 2 Bar objects, but how do we check which ones they are? Lets add a __repr__ method to Bar so it is more informative
>>> Bar.__repr__=lambda self:"Bar(occupants={0})".format(self.occupants)
>>> foo
[Bar(occupants=2), Bar(occupants=3)]
I am an absolute beginner in programming, so please forgive my utter lack of understanding.
I came across this concept quite recently through a course I am taking in Python. I re-watched the lessons, I have tried doing some separate research on this topic, but I am still having a hard time wrapping my head around it.
The project I am currently working on is a random password generator. I was stumped and couldn't figure it out on my own so I watched the teacher's solution as a last resort. Especially puzzled when she used this code:
password = ""
for char in password_list:
password += charFor context, this code is supposed to convert a list of characters (from password_list) into a string.
I thought that for loops were used for iteration. I am only familiar with using "for __ in __ range(a, b)" so far, so I was quite puzzled by this loop as I don't understand how it works. Could someone please help me break it down into simpler terms? That would be super appreciated.
Please and thank you.