2

I have had experience in Java/C#/C++ and for loops or pretty much if not exactly done the same. Now I'm learning Python through Codecademy. I find it poor the way it trys to explain for loops to me. The code they give you is

my_list = [1,9,3,8,5,7]

for number in my_list:
    # Your code here
    print 2 * number

Is this saying for every number in my_list ... print 2 * number. That somewhat makes sense to me if that's true but I don't get number and how that works. It's not even a variable declared earlier. Are you declaring a variable withing the for loop? And how does Python know that number is accessing the values within my_list and multiplying them by 2? Also, how do for loops work with things other than lists because I've looked at other Python code that contains for loops and they make no sense. Could you please find some way to explain the way these are similar to something like C# for loops or just explain Python for loops in general.

freemann098
  • 284
  • 1
  • 7
  • 22

8 Answers8

1

The quick answer, to relate to C#, is that a Python for loop is roughly equivalent to a C# foreach loop. C++ sort of has similar facilities (BOOST_FOREACH for example, or the for syntax in C++11), but C does not have an equivalent.

There is no equivalent in Python of the C-style for (initial; condition; increment) style loop.

Python for loops can iterate over more than just lists; they can iterate over anything that is iterable. See for example What makes something iterable in python.

Community
  • 1
  • 1
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
1

Yes, number is a newly defined variable. Python does not require variables to be declared before using them. And the understanding of the loop iteration is correct.

This is the same sytnax Borne-style shells use (such as bash).

The logic of the for loop is this: assign the named variable the next value in the list, iterate, repeat.

correction As for other non-list values, they should translate into a sequence in python. Try this:

val="1 2 3"
for number in val:
        print number

Note this prints "1", " ", "2", " ", "3".

Here's a useful reference: http://www.tutorialspoint.com/python/python_for_loop.htm.

ash
  • 4,867
  • 1
  • 23
  • 33
  • Section 5.6 of this page explains sequences: http://docs.python.org/2/library/stdtypes.html – ash Aug 27 '13 at 04:05
1

Python doesn't need variables to be declared it can be declared itself at the time of initialization

While and do while are similar to those languages but for loop is quite different in python

you can use it for list similar to for each but for another purpose like to run from 1 to 10 you can use,

for number in range(10):
    print number
Anto
  • 610
  • 5
  • 13
0

Python for loops should be pretty similar to C# foreach loops. It steps through my_list and at each step you can use "number" to reverence to that element in the list.

If you want to access list indices as well as list elements while you are iterating, the usual idiom is to use g the "enumerate function:

for (i, x) in enumerate(my_list):
   print "the", i, "number in the list is", x

The foreach loop should should be similar to the following desugared code:

my_iterator = iter(my_list)
while True:
   try:
     number = iter.next()
     #Your code here
     print 2*number
   except StopIteration:
      break
hugomg
  • 68,213
  • 24
  • 160
  • 246
0

In Python you don't need to declare variables. In this case the number variable is defined by using it in the loop.

As for the loop construct itself, it's similar to the C++11 range-based for loop:

std::vector<int> my_list = { 1, 9, 3, 8, 5, 7 };

for (auto& number : my_list)
    std::cout << 2 * number << '\n';

This can of course be implemented pre-C++11 using std::for_each with a suitable functor object (which may of course be a C++11 lambda expression).

Python does not have an equivalent to the normal C-style for loop.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Python uses protocols (duck-typing with specially named methods, pre and post-fixed with double underscores). The equivalent in Java would be an interface or an abstract base class.

In this case, anything in Python which implements the iterator protocol can be used in a for loop:

class TheStandardProtocol(object):
    def __init__(self):
        self.i = 0

    def __iter__(self):
        return self

    def __next__(self):
        self.i += 1
        if self.i > 15: raise StopIteration()
        return self.i

    # In Python 2 `next` is the only protocol method without double underscores
    next = __next__


class TheListProtocol(object):
    """A less common option, but still valid"""
    def __getitem__(self, index):
        if index > 15: raise IndexError()
        return index

We can then use instances of either class in a for loop and everything will work correctly:

standard = TheStandardProtocol()
for i in standard:  # `__iter__` invoked to get the iterator
    # `__next__` invoked and its return value bound to `i`
    # until the underlying iterator returned by `__iter__`
    # raises a StopIteration exception
    print i

# prints 1 to 15

list_protocol = TheListProtocol()
for x in list_protocol:  # Python creates an iterator for us
    # `__getitem__` is invoked with ascending integers
    # and the return value bound to `x`
    # until the instance raises an IndexError
    print x

# prints 0 to 15

The equivalent in Java is the Iterable and Iterator interface:

class MyIterator implements Iterable<Integer>, Iterator<Integer> {
    private Integer i = 0;

    public Iterator<Integer> iterator() {
        return this;
    }

    public boolean hasNext() {
        return i < 16;
    }

    public Integer next() {
        return i++;
    }
}

// Elsewhere

MyIterator anIterator = new MyIterator();

for(Integer x: anIterator) {
    System.out.println(x.toString());
}
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
0

Pretty similar to this Java loop: Java for loop syntax: "for (T obj : objects)"

In python there's no need to declare variable type, that's why number has no type.

Community
  • 1
  • 1
Drakosha
  • 11,925
  • 4
  • 39
  • 52
0

I will try to explain the python for loop to you in much basic way as possible:

Let's say we have a list:

a = [1, 2, 3, 4, 5]

Before we jump into the for loop let me tell you we don't have to initialize the variable type in python while declaring variable.

int a, str a is not required.

Let's go to for loop now.

for i in a:
    print 2*i

Now, what does it do?

The loop will start from the first element so,

i is replaced by 1 and it is multiplied by 2 and displayed. After it's done with 1 it will jump to 2.

Regarding your another question:

Python knows its variable type in it's execution:

>>> a = ['a', 'b', 'c']
>>> for i in a:
...     print 2*i
... 
aa
bb
cc
>>> 
Joyfulgrind
  • 2,762
  • 8
  • 34
  • 41