How can I make this function into a loop? Python

Viewed 63

I would like to call again the function to return a new list with 5 results of sampled_list. Thank you guys

import random
emoji_list  = ['', '', '', '', '', '', '', '','', '', '', '', '', '', '', '', '', '','', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

sampled_list=random.sample(emoji_list, k=5)

def listToString(sampled_list):
    # initialize an empty string
    str1 = ""
    # traverse in the string
    for i in sampled_list:
        str1 += i
        # return string
    return str1
1 Answers

Probably you wanted something like this:

Try it online!

import random

def emojiString():
    emoji_list  = ['', '', '', '', '', '', '', '','', '', '', '', '', '', '', '', '', '','', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
    return ''.join(random.sample(emoji_list, k = 5))

print(emojiString())
print(emojiString())

Output:




If you want to accumulate several results into list do following:

Try it online!

import random

def emojiString():
    emoji_list  = ['', '', '', '', '', '', '', '','', '', '', '', '', '', '', '', '', '','', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
    return ''.join(random.sample(emoji_list, k = 5))

def emojiAddToList(l):
    l.append(emojiString())

l = []
emojiAddToList(l)
emojiAddToList(l)
emojiAddToList(l)
print(l)

Output:

['', '', '']
Related