I want to add two elements at the same time to understanding the list. One element is permanent. How can this be achieved using only one cycle inside the list comprehension and no additional functions. Responses that do not use import will be approved.
Take a look 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 create a list with the ^ character that was added before each letter in lower case. In this example, you need to use sum to flatten the list. However, my question is whether it is possible to make a flat list in the first place. The above output is the desired output.
As in, add something constantly before the variable, which changes with each iteration of the for loop. You 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 you are doing 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 in lists. Thus, is there a way in which you can add two elements at the same time in list comprehension without using a loop add-on or an add-on function like sum ? I ask about it because it is something rather simple, but I cannot find a way to do this. If you try to do the following:
>>> ['^', x for x in mystring.lower()] File "<console>", line 1 ['^', x for x in mystring.lower()] ^ SyntaxError: invalid syntax
Trying gives SyntaxError . So what am I asking to do in Python? Using () gives me a list of tuples.
I also tried using the splat / unpacking :
>>> [*['^', x] for x in mystring.lower()] File "<console>", line 1 [*['^', x] for x in mystring.lower()] ^ SyntaxError: invalid syntax
But, as above, this is also a syntax error. Sorry for this late change, but I tried the following:
import itertools mystring = "HELLOWORLD" print(list(itertools.chain.from_iterable(('^', x) for x in mystring.lower())))
But above, import is still required.