Python – Concatenate Random characters in String List

Given a String list, perform concatenaton of random characters.

Input : test_list = [“Gfg”, “is”, “Best”, “for”, “Geeks”]
Output : “GiBfe”
Explanation : Random elements selected, e.g G from Gfg, etc.

Input : test_list = [“Gfg”, “is”, “Best”]
Output : “fst”
Explanation : Random elements selected, e.g t from Best, etc.

Method #1 : Using loop + random.choice()

In this, we extract random character using choice() and perform task of iteration using loop. The character concatenation is done using + operator.



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Concatenate Random characters in String List
# Using loop + choice()
import random
  
# initializing list
test_list = ["Gfg", "is", "Best", "for", "Geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = ''
for ele in test_list:
      
    # Concatenating random elements
    res += random.choice(ele)
          
# printing results
print("Concatenated String : " + str(res))

chevron_right


Output

The original list is : ['Gfg', 'is', 'Best', 'for', 'Geeks']
Concatenated String : Gsere

Method #2 : Using list comprehension + choice() + join()

In this, we perform task of getting random using choice() and concatenation is done using join().

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Concatenate Random characters in String List
# Using list comprehension + choice() + join()
import random
  
# initializing list
test_list = ["Gfg", "is", "Best", "for", "Geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# characters joining using join()
res = ''.join([random.choice(ele) for ele in test_list])
          
# printing results
print("Concatenated String : " + str(res))

chevron_right


Output

The original list is : ['Gfg', 'is', 'Best', 'for', 'Geeks']
Concatenated String : Gitrk



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.