Flowchart Iterating through List

Question:

Let say I have a list l

l = ['a', 'b', 'c']

To iterate through the list,

for i in l:
    # <some function>

My problem is how should I represet it in a flowchart? Should I use i as index? Thanks in advance.

Asked By: Cheah Ken Win

||

Answers:

Flowcharts are rather miserable for loops

Here is the usual way to do it (from http://etutorials.org/Programming/visual-c-sharp/Part+I+Introducing+Microsoft+Visual+C+.NET/Chapter+5+Flow+of+Control/Building+Loops+Using+Iteration+Statements/)

enter image description here

Flowcharts work best for branching workflows with lots of "ifs"

As you progress, you are getting into smaller and smaller subsets of the overall chart.

They can work for looping, of the type of while do or do while, because these inherently tell you to jump back to a point (or skip over a block).

But for looping controlled by a variable, it’s ugly, I’m afraid.

In your specific case, you could use these terms:

Initialization:

  • Set index to 0

Conditional expression

  • Is #index item still within the list? i.e. is index < len(list)?
  • If false, arrow down to end
  • If true, continue to "Controlled statement"

Controlled statement

  • <Some function>

Iteration statement

  • Increment index
  • Go back to "Conditional expression"
Answered By: ProfDFrancis

If it’s just in terms of the title, your question is how do you represent it in the flow chart? Whether i is an index,

That’s how you represent the for loop,

In general, you have to have a loop initialization condition, a loop judgment, a loop condition change, and i doesn’t mean index

So for loops might not be very easy to understand in python, because it doesn’t have that, and it might make you wonder why you’re using for directly, and you might even wonder if you’re going through the underlying index,

Then you need to say that python’s for loop causes problems,

python everything is object,

What we call a for loop is actually a foreach loop

Let’s see if we’re using an index,

Let’s do this with a while loop

num_list = [1, 2, 3, 4]

index = 0
while index < len(num_list):
    print(num_list[index])
    index += 1
num_set = {1, 2, 3, 4}

index = 0
while index < len(num_set):
    print(num_set[index])
    index += 1

Traceback (most recent call last):
  File "/home/test.py", line 12, in <module>
    print(num_set[index])
TypeError: 'set' object is not subscriptable

The for loop is aimed at an iterable form

So what you really need to describe is this iterable type, which python implements

Answered By: chrisfang
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.