-4
import string
letters=string.ascii_lowercase
letters

'abcdefghijklmnopqrstuvwxyz'

we are looking to convert letters into a list of length 26^2, featuring all unordered pairings of letters ['aa', 'ab', 'ac', ..., 'az', 'ba', 'bb', 'bc', ..., 'zz']. I am looking to avoid code that looks like this:

letter_list = []
for letter1 in letters:
    for letter2 in letters:
        letter_list.append(f'{letter1}{letter2}')

Is there a 1 liner with nested list comprehension?

Canovice
  • 9,012
  • 22
  • 93
  • 211
  • 3
    `[x + y for x in letters for y in letters]`? – j1-lee Jan 06 '22 at 02:05
  • 3
    Does this answer your question? [What is the best way to generate all possible three letter strings?](https://stackoverflow.com/questions/7074051/what-is-the-best-way-to-generate-all-possible-three-letter-strings) (Yes, it's for 3-letter strings but it's the same solution for 2-letter strings, just need to adjust the itertools param or the non-itertools loop solutions). – Gino Mempin Jan 06 '22 at 02:07
  • With https://docs.python.org/3/library/itertools.html#itertools.combinations: `combinations('abcdefghijklmnopqrstuvwxyz', 2)` – PM 77-1 Jan 06 '22 at 02:09

1 Answers1

-5

A nested loop is probably the right way...Sorry about that

Try:

letter_list = []
letters = 'abcdefg...'
letters = list(letters)
for x in letters:
    for y in letters:
         letter_list.append(x+y)

Sorry that it is a nested loop. I don't think that making it a single line will be very easy, and probably won't be worth it, because users don't usually look at the back-end. Good luck!

-Codeitfast

Codeitfast
  • 169
  • 13