Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for-loop without index and item

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?

like image 800
jonie83 Avatar asked Jul 24 '14 08:07

jonie83


People also ask

How do you find the index of an element in a for loop Python?

Let us see how to check the index in for loop in Python. To check the index in for loop you can use enumerate() function. In Python, the enumerate() is an in-built function that allows us to loop over a list and count the number of elements during an iteration with for loop.

Is enumerate faster than for loop?

Using enumerate() is more beautiful but not faster for looping over a collection and indices.

Does Python loop start at 0?

Similar to any other programming language, the starting index of the for loop is 0 by default. However, the range of the iteration statement can be manipulated, and the starting index of the loop can be changed to 1 .

How do you iterate over a list length?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.


2 Answers

You can replace i with _ to make it an 'invisible' variable.

See related: What is the purpose of the single underscore "_" variable in Python?.

like image 93
toine Avatar answered Sep 23 '22 07:09

toine


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.

like image 43
Windowlicker Avatar answered Sep 19 '22 07:09

Windowlicker