0

I'm used to seeing For Loops in this format:

for number in l: sum = sum + number

I was browsing some forums and came across this piece of code:

count_chars = ".arPZ" string = "Phillip S. is doing a really good job." counts = tuple(string.count(d) for(d) in count_chars) print counts 

I'm not sure if that is really a For loop, so I decided to rewrite it in a way that I understood:

tuple( for(d) in count_chars: string.count(d)) 

Needless to say, it failed lol. So can someone explain what is going on, and explain the folly of my logic? Thanks!!

5

1 Answer 1

4

It's not quite a for loop as such, but a generator expression. What it basically does is return an iterator where each element is the amount of time every character in count_chars occurs in d. It then adds all of these elements into a tuple.

It is (roughly) equivalent to:

counts = [] for d in count_chars: counts.append(string.count(d)) counts = tuple(counts) 
Sign up to request clarification or add additional context in comments.

2 Comments

@user3386440 declare an empty list counts. For every element in count_chars, count how many times it is in string and add that number to the list counts. Convert counts to a tuple.
Thanks again. I'll look up append on my own but I think I got the rest of it. Assume I didn't want it to appear on a list ie: (2,2,1,1,0). Instead I want it to be be simply print out. I will show you want I mean in the OP.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.