I want to add two items at a time to a list comprehension. One item is constant. How can this be achieved using only one for loop inside of a list comprehension, and no additional functions. Answers that do not use any import will be favored.
Take a look at at the following:
>>> mystring = 'ABCELKJSDLHFWEHSJDHFKHIUEHFSDF'
>>> sum([['^', char] for char in mystring.lower()], [])
['^', 'a', '^', 'b', '^', 'c', '^', 'e', '^', 'l', '^', 'k', '^', 'j', '^', 's', '^', 'd', '^', 'l', '^', 'h', '^', 'f', '^', 'w', '^', 'e', '^', 'h', '^', 's', '^', 'j', '^', 'd', '^', 'h', '^', 'f', '^', 'k', '^', 'h', '^', 'i', '^', 'u', '^', 'e', '^', 'h', '^', 'f', '^', 's', '^', 'd', '^', 'f']
I am trying to make a list with the character ^
prepended before each letter in lower case. In this example, you need to use sum
to flatten the list. However, my question is, if it is possible to make a flat list in the first place. The output above is the desired output.
As in, append something constantly before a variable that changes with each iteration of the for
loop. One cannot use two for
loops here, as that would be too simple, for example:
mystring = 'ABCELKJSDLHFWEHSJDHFKHIUEHFSDF'
print [item for x in mystring.lower() for item in ['^', x]]
If one does something like this:
>>> mystring = 'ABCELKJSDLHFWEHSJDHFKHIUEHFSDF'
>>> [['^', x] for x in mystring]
['^', 'a', '^', 'b', '^', 'c', '^', 'e', '^', 'l', '^', 'k', '^', 'j', '^', 's', '^', 'd', '^', 'l', '^', 'h', '^', 'f', '^', 'w', '^', 'e', '^', 'h', '^', 's', '^', 'j', '^', 'd', '^', 'h', '^', 'f', '^', 'k', '^', 'h', '^', 'i', '^', 'u', '^', 'e', '^', 'h', '^', 'f', '^', 's', '^', 'd', '^', 'f']
You get lists within lists. Thus, is there a way that you can append two items at a time in a list comprehension without have to use an addition for loop or an additional function like sum
? I ask this, because its something quite simple, yet I can't find a way to do it. If one tries to do the following:
>>> ['^', x for x in mystring.lower()]
File "<console>", line 1
['^', x for x in mystring.lower()]
^
SyntaxError: invalid syntax
The attempt gives a SyntaxError
. So, is what I'm asking impossible to do in Python? Using ()
gives me a list of tuples.
I've also tried using the splat
/unpacking
operator:
>>> [*['^', x] for x in mystring.lower()]
File "<console>", line 1
[*['^', x] for x in mystring.lower()]
^
SyntaxError: invalid syntax
But as above, this too is a syntax error. Sorry for this late edit, but I have tried the following:
import itertools
mystring = "HELLOWORLD"
print(list(itertools.chain.from_iterable(('^', x) for x in mystring.lower())))
But the above still required an import.