Python: Merge Multiline Output into Singular List

99 Views Asked by At

I created a random generator to create a list with a set amount of strings. Each string is a mix of uppercase letters and digits. I then got the number of characters in each string. However, the output is coming out as it's own individual line. I need these output lines to result in a new list.

Current Output:

5

1

2
Desired Output: (5,1,2)

I am very new to python, please help. Below is my code so far:

import random
import string

chars = string.ascii_uppercase + string.digits
from random import randrange
A = [''.join(random.choices(string.ascii_uppercase + string.digits, k=randrange(1,10))) for j in range(5)]

print(A)


def bubbleSort(A):
    for passnum in range(len(A)-1,0,-1):
        for i in range(passnum):
            if A[i]>A[i+1]:
                temp = A[i]
                A[i] = A[i+1]
                A[i+1] = temp

bubbleSort(A)
print(A)


#Output line 1: Original List
#Output line 2: Sorted List


for item in A:
  len(item)
  A2 = len(item)
  print(A2)
2

There are 2 best solutions below

1
Michael Bianconi On

Use print(A2, end=', ') in your final loop to print the items on the same line.

0
Fred Larson On

You could use a list comprehension instead of your last for loop:

print([len(item) for item in A])

Possible output of your posted code using this list comprehension in place of the loop:

['XXF8XQA2V', 'ACQ1A782', 'E', '6G1LC45', 'C']
['6G1LC45', 'ACQ1A782', 'C', 'E', 'XXF8XQA2V']
[7, 8, 1, 1, 9]