82

In C/C++, I can have the following loop

for(int k = 1; k <= c; k += 2)

How do the same thing in Python?

I can do this

for k in range(1, c):

In Python, which would be identical to

for(int k = 1; k <= c; k++)

in C/C++.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
newprint
  • 6,936
  • 13
  • 67
  • 109

11 Answers11

93

Try using this:

for k in range(1,c+1,2):
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
carlosdc
  • 12,022
  • 4
  • 45
  • 62
  • 8
    as a side note if you are using python 2.x xrange is more efficient. – GWW Nov 13 '10 at 02:42
  • 5
    @GWW: xrange is technically more _memory_ efficient, but it's rarely of any practical consequence unless your range is extremely large, and 3.x does away with the name 'xrange' entirely, so using it is more likely to confuse newbies than anything else. – Nicholas Knight Nov 13 '10 at 02:58
  • @Nicholas: I'm just mentioning it, I really am not trying to confuse. I learned about xrange the hard way when I had range causing a massive bottle neck in my code. I don't want anyone else to get stuck on that :P – GWW Nov 13 '10 at 03:03
  • 4
    @Nicholas Knight. I've done testing and `for i in xrange(1)` is faster than `for i in range(1)` significantly enough to never use `range` unless you actually want to construct a list. The increase in speed only increases as the size of the sequence increases. – aaronasterling Nov 13 '10 at 03:13
  • 1
    While I do encourage using python3 compatible constructs, note that "2to3" will convert an xrange to range. The recommendation, AFAIK, is to program for 2.7 and use 2to3 to convert the code to 3.x, so I would encourage the use of xrange(), the preferred 2.x construct. – Sean Reifschneider Nov 13 '10 at 03:20
  • @aaronasterling: Not sure what ranges you're dealing with, but in my applications, the difference is on the order of 50-100 microseconds per loop. @Sean: Who's making that recommendation? Unless someone has explicitly stated a need to maintain 2.x compatibility, such a recommendation is not only silly, it's counterproductive. – Nicholas Knight Nov 13 '10 at 03:39
  • actually it is: for x in sequence: So, Better understand the data structure in python clearly. – Tauquir Nov 13 '10 at 03:50
  • @Nicoloas Knight, the difference of 50-100 microseconds is absolutely enough to justify typing the extra character unless you _need_ a list. – aaronasterling Nov 13 '10 at 07:05
  • 2
    @aaronasterling: Perhaps you misunderstood, 50-100 microseconds per _loop_, not per _iteration_. If you care about that kind of speed, you shouldn't be using Python in the first place. And it's not about justifying the extra character, it's about the needless confusion for newbies who are going to be coming back here on py3k and saying "I was told to use xrange, but it's not there!". – Nicholas Knight Nov 13 '10 at 07:37
  • @Nicholas Knight - I understood perfectly. I think that the fact that it's faster (even if only very moderately), is not bad for readability and is better for memory make it the right thing. If that's too tough for a noob then oh well. When it's not there, look it up in the manual and find out why. If we let the lowest common denominator control best practices then we might as well all program in PHP and Visual Basic. – aaronasterling Nov 13 '10 at 08:31
  • If using the code above, do you have to pre-define k or is it created on the fly? If it doesn't have to be pre-defined, what happens to it when the for loop ends? – Stuart Jeckel Sep 11 '18 at 20:01
59

You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.

mylist = [1,2,3]
for item in mylist:
    print item

mydict  = {1:'one', 2:'two', 3:'three'}
for key in mydict:
    print key, mydict[key]

This is actually faster than using the above code with range(), and removes the extraneous i variable.

If you need to edit items of a list in-place, then you do need the index, but there's still a better way:

for i, item in enumerate(mylist):
    mylist[i] = item**2

Again, this is both faster and considered more readable. This one of the main shifts in thinking you need to make when coming from C++ to Python.

bukzor
  • 37,539
  • 11
  • 77
  • 111
  • 4
    Nothing in the question (right back to the first revision) says anything about iterating through array or even mentions an array at all. For-loops aren't just for iterating through arrays, they're also used for *counting*. What if you wanted to simply print "Hello World" five times? How would you do that without a counter? – Synetech May 19 '20 at 01:21
  • That's true, but I never said "never use `range`". My two suggestions start with "if". Iterating "directly" rather than via an integer variable is one of the things everyone has to un-learn when coming to Python. At least 90% of the time I see a junior programmer write `for i in range`, the correct refactoring is to get rid of range. The accepted answer makes me believe that was true here, as well. It's also interesting to note that the idiomatic way to do "just counting" in python (`for i in range(x):`) is *actually iterating through a list* of integers, rather than incrementing a counter. – bukzor Aug 08 '20 at 20:02
  • Just for fun: `print("\n".join(["Hello, world!"] * 5))` – bukzor Aug 08 '20 at 20:04
31

The answer is good, but for the people that want this with range(), the form to do is:

range(end):

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(start,end):

 >>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

range(start,end, step):

 >>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
15

If you want to write a loop in Python which prints some integer no etc, then just copy and paste this code, it'll work a lot

# Display Value from 1 TO 3  
for i in range(1,4):
    print "",i,"value of loop"

# Loop for dictionary data type
  mydata = {"Fahim":"Pakistan", "Vedon":"China", "Bill":"USA"  }  
  for user, country in mydata.iteritems():
    print user, "belongs to " ,country
jay.sf
  • 60,139
  • 8
  • 53
  • 110
Pir Fahim Shah
  • 10,505
  • 1
  • 82
  • 81
8

In Python you generally have for in loops instead of general for loops like C/C++, but you can achieve the same thing with the following code.

for k in range(1, c+1, 2):
  do something with k

Reference Loop in Python.

Octane
  • 1,200
  • 11
  • 11
3

In C/C++, we can do the following, as you mentioned

for(int k = 1; k <= c ; k++)
for(int k = 1; k <= c ; k +=2)

We know that here k starts with 1 and go till (predefined) c with step value 1 or 2 gradually. We can do this in Python by following,

for k in range(1,c+1):
for k in range(1,c+1,2):

Check this for more in depth.

Innat
  • 16,113
  • 6
  • 53
  • 101
1

The range() function in python is a way to generate a sequence. Sequences are objects that can be indexed, like lists, strings, and tuples. An easy way to check for a sequence is to try retrieve indexed elements from them. It can also be checked using the Sequence Abstract Base Class(ABC) from the collections module.

from collections import Sequence as sq
isinstance(foo, sq)

The range() takes three arguments start, stop and step.

  1. start : The staring element of the required sequence
  2. stop : (n+1)th element of the required sequence
  3. step : The required gap between the elements of the sequence. It is an optional parameter that defaults to 1.

To get your desired result you can make use of the below syntax.

range(1,c+1,2)
NAND
  • 663
  • 8
  • 22
hyder47
  • 11
  • 2
1

You can use the below format.

for i in range(0, 10, 2):
    print(i,' ', end='')
print('')

and this will print;

0  2  4  6  8 
Kalhara Tennakoon
  • 1,302
  • 14
  • 20
0

Despite asking a FOR STATEMENT, just for the record as bonus, alternatively with WHILE, it'd be:

k=1
while k<c:
      #
      # your loop block here
      #
      k+=2
PYK
  • 3,674
  • 29
  • 17
-1

Here are some example to iterate over integer range and string:

#(initial,final but not included,gap)
for i in range(1,10,2): 
  print(i); 
1,3,5,7,9

# (initial, final but not included)  
# note: 4 not included
for i in range (1,4): 
   print(i);
1,2,3 

#note: 5 not included
for i in range (5):
  print (i);
0,1,2,3,4 

# you can also iterate over strings
myList = ["ml","ai","dl"];  

for i in myList:
  print(i);
output:  ml,ai,dl
demokritos
  • 1,416
  • 2
  • 12
  • 34
RITTIK
  • 149
  • 1
  • 5
-3

Use this instead of a for loop:

k = 1
while k <= c:
   #code
   k += 1