Home > Back-end >  How to print nested list into charter side by side in python
How to print nested list into charter side by side in python

Time:12-11

In python

a = [['z', 'G', 'j', 'E', 'U'], ['%', '#', '(', '!', ')'], ['6', '4', '8', '1', '3']]

I want to print above nested list into character which are side by side example output:

zGjEU%#(!)64813

How to do that?

CodePudding user response:

Consider a nested comprehension along with str.join:

>>> a = [['z', 'G', 'j', 'E', 'U'], ['%', '#', '(', '!', ')'], ['6', '4', '8', '1', '3']]
>>> print(''.join(c for chars in a for c in chars))
zGjEU%#(!)64813

CodePudding user response:

To print the elements of a nested list side by side in Python, you can use the join method on the string representation of each element of the nested list. Here is an example of how to do this:

a = [['z', 'G', 'j', 'E', 'U'], ['%', '#', '(', '!', ')'], ['6', '4', '8', '1', '3']]

# Loop over the nested list
for row in a:
    # Convert each element of the list to a string and join them using ''
    print(''.join(str(x) for x in row))

CodePudding user response:

a = [['z', 'G', 'j', 'E', 'U'], ['%', '#', '(', '!', ')'], ['6', '4', '8', '1', '3']]
result = ""
for item in a:
    for char in item:
        result  = char

result:

'zGjEU%#(!)64813'
  • Related