Printing this type of list

Question:

I want to create a list like this:

mylist = ['a', 'ab', 'abc', 'abcd']

Is there any way to do this?

Asked By: tofi1130

||

Answers:

I cant comment but could you clarify? this is very confusing like do you want to print each item in the list?

Here’s the code if thats what you want to do:

mylist = ['a', 'ab', 'abc', 'abcd']
for i in mylist:
    print(i)
Answered By: Zen35X

You can use a format printing.

print("{} = ['{}', '{}', '{}', '{}']".format(mylist, varA, varB, varC, varD))
Answered By: holeInAce
def generate_list(start='a', end='d'):
    mylist = []
    start, end = ord(start), ord(end)
    for i in range(start, end + 1):
        sublist = [chr(j) for j in range(start, i + 1)]
        mylist.append(''.join(sublist))
    return mylist

mylist = generate_list()
print(mylist)

prints

['a', 'ab', 'abc', 'abcd']

another example:

mylist2 = generate_list(end='f')
print(mylist2)

prints

['a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef']
Answered By: Michael Hodel

Are you meaning appending letters to the list in alphabetical order and printing than out?

import string

n = 5
mylist = []
for i in range(1, n + 1):
    mylist.append("".join([letter for letter in string.ascii_lowercase[:i]]))
print(mylist) 

will get result ['a', 'ab', 'abc', 'abcd', 'abcde'].

Or you could get each value by running

for value in mylist:
    print(value)
Answered By: josix
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.