0

Here is my current code:

My issue is, I'm practicing List Comprehension but am confused as to why "count += 1" does not work in this type of format:

[count += 1 for elem in li]
[count += 1 and print(elem) for elem in li]

I am, however, able to do it in a normal for loop as I did below. Can someone explain how I can accomplish the function below with a list comprehension?

(The above lines of code with the list comprehension format are not necessarily related to accum(s).)

def accum(s):
    count = 0
    li = []
    for char in s:
        count += 1
        li.append(char.upper() + char.lower() * (count-1))
    return "-".join(li)
Alex R
  • 25
  • 3

3 Answers3

2

Comprehensions take an expression as its first element; count += 1 is a statement.

Instead, use enumerate, which takes a generator producing x and returns a generator producing (i, x) where i is the index:

'-'.join(char.upper() + char.lower() * i for i, char in enumerate(s))
Amadan
  • 191,408
  • 23
  • 240
  • 301
1
for count,char in enumerate(s):
    li.append(char.upper() + char.lower() * (count-1))

use enumerate for this type of thing

as a list comprehension

  [char.upper() + char.lower() * (count-1) for count,char in enumerate(s)]
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

if you want to maintain count in python list comprehension, use enumerate

check this answers

and try this code

"-".join((elem.upper() + elem.lower() * i) for ii, elem in enumerate(li))

minji
  • 512
  • 4
  • 16