This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 7 months ago.
Is it possible in python to have a for-loop without index and item?
I have something like the following:
list_1 = []
for i in range(5):
list_1.append(3)
The code above works fine, but is not nice according to the pep8 coding guidelines.
It says: "Unused variable 'i'".
Is there a way to make a for-loop (no while-loop) without having neither the index nor the item? Or should I ignore the coding guidelines?
You can replace i with _ to make it an 'invisible' variable.
See related: What is the purpose of the single underscore "_" variable in Python?.
While #toine is completly right about using _, you could also refine this by means of a list comprehension:
list_1 = [3 for _ in range(5)]
This avoids the ITM ("initialize, than modify") anti-pattern.
Related
This question already has answers here:
Use cases for the 'setdefault' dict method
(18 answers)
Closed 4 months ago.
I have found myself writing code like this fairly often:
nums = {}
allpngs = [ii for ii in os.listdir() if '.png' in ii]
for png in allpngs:
regex = r'(.*)(\d{4,})\.png'
prefix = re.search(regex, png).group(1)
mynum = int(re.search(regex, png).group(2))
if prefix in nums.keys():
nums[prefix].append(mynum)
else:
nums[prefix] = [mynum]
Essentially, I'm wanting to create a dictionary of lists where the keys are not known ahead of time. This requires the if statement you see at the bottom of the for loop. I seem to write this pretty frequently, so I'm wondering if there's a shorter / more pythonic way of doing this.
To be clear, what I have works fine, but it would be nice if I could do it in fewer lines and still have it be readable and apparent what's happening.
Thanks.
You can use dict.setdefault:
...
nums.setdefault(prefix, []).append(mynum)
...
This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
How can I get around declaring an unused variable in a for loop?
(10 answers)
Closed 1 year ago.
I'm looking at some tensorflow stuff and I understand for loops or atleast I think I do, however I came across for _ in range(20) and was wondering what is the meaning of the _ in this case. I am used to for x in range or for i in range stuff and understand those but haven't been able to understand what i've read on the underscore
When you are not interested in some values returned by a function we use underscore in place of variable name . Basically it means you are not interested in how many times the loop is run till now just that it should run some specific number of times overall.
This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 3 years ago.
At 44:05 in his Fun of Reinvention talk, Dave Beasley writes
>>> d = _
There is a lot before that, which is necessary for the result he gets. But ignoring the output, what does that input line mean? Whenever I try it, either in a file in the PyCharm editor, in the PyCharm Python console, using straight IDLE (all v3.7) I get an error.
Any idea what this may mean and how to get something like that to run?
Thanks
_ is a special variable in the python language.
In some REPLs, like IDLE, it holds the result of the last expression executed.
d = _ assigns the result of the last expression executed to d.
This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 4 years ago.
This is going to be a bit silly of a question. I have a simple list:
my_list = ["apple", "orange", "car"]
And I'd like to run a loop for the length of that list, but I don't need anything in the list. I can clearly do this:
for item in my_list:
call_external_thingy()
Which would loop 3 times, perfect. However, I'm never using the item in my for loop. So while this does work, everytime I look at my code I feel that I've made a mistake, "Oh shoot, I didn't pass item in.. oh right I just need to run that command for the number of items in the list..."
What would be the more pythonic way to simply run a for loop for the number of items in a list without creating item. I'm thinking of something with len or range but can't get my head around it and anything I mock up just looks like a big mess.
Note, I'm tempted to put this on codereview instead, but they usually want all the code and a lot of why. This seems like a simple enough question to be here, but I could be wrong!
Thank you!
This is pythonic :
for _ in my_list:
call_external_thingy()
for i in range(len(my_list)):
call_external_thingy()
This question already has answers here:
cleanest way to call one function on a list of items
(1 answer)
Is it Pythonic to use list comprehensions for just side effects?
(7 answers)
Closed 5 years ago.
I know that for creating lists you can shorten a few lines down to something like (in python):
a = [k*2 for k in range(10)]
Can you do this for when sending data through a pipe. (using multiprocessing module in this case). eg:
k = 'hello'
[channel.send(k) for channel in channels]
instead of:
k = 'hello'
for channel in channels:
channel.send(k)
Any suggestions would be great! Thanks in advance.
EDIT: Has been answered. List comprehensions bad idea. Just keep it neat to one line:
k = 'hello'
for channel in channels: channel.send(k)
No. List comprehensions are for creating lists. If you don't want the list, don't use a list comprehension. There is nothing wrong with using a for loop when it is the appropriate thing to use.