-1

I have written a code that prints all letters, but I want to take its output to put it in a variable. i.e. I want to take all letters and save it in one variable instead of writing all letters manually.

for letter in range(97, 123):
    letters = chr(letter)
    print(letters, end=" ")
martineau
  • 119,623
  • 25
  • 170
  • 301
iis2h
  • 21
  • 3

1 Answers1

3

If you wish to complete this in one line, Python has a neat way of allowing you to create lists with the use of list comprehensions. If you wish to know more about what a list comprehension is, you may see point 5.1.3 here.

letters = [chr(letter) for letter in range(97, 123)]

A more comprehensible way of solving the problem is to append the characters to a letters list which should be defined before you begin to loop your range.

letters = []
for letter in range(97, 123):
    letters.append(chr(letter))

print(letters)

The Python documentation does a good job of explaining the different data structures used throughout the programming language, I hope this clears up the various ways to solve your problem described.

Aidan Donnelly
  • 369
  • 5
  • 19