Home > OS >  Printing this type of list
Printing this type of list

Time:08-08

I want to create a list like this:

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

Is there any way to do this?

CodePudding user response:

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)

CodePudding user response:

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']

CodePudding user response:

You can use a format printing.

print("{} = [\'{}\', \'{}\', \'{}\', \'{}\']".format(mylist, varA, varB, varC, varD))

CodePudding user response:

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)
  • Related