Joe Deer
Joe Deer

Reputation: 35

How to combine inner list into a string

I have a list of lists. I am trying to combine the inner list of characters into one string.

For example:

values = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
newValues =['abc', 'def', 'ghe']

This is what I have but it's not working. I can't figure out how to get the syntax to work. :/

values = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

for i in values:
    print(" ".join(values[i]))

Upvotes: 0

Views: 61

Answers (2)

David Buck
David Buck

Reputation: 3830

You're on the right lines, you can either use a list comprehension like:

new_values = ["".join(sub_list) for sub_list in values]

Or a for loop:

new_values = []
for sub_list in values:
    new_values.append("".join(sub_list))

Both output:

['abc', 'def', 'ghi']

A couple of notes about your code:
Your loop won't work as you've written it as for i in values means that every value of i will contain a sub list, not an index to it, so to print it out as you have in your example, you would either need to do:

for i in range(len(values)):  # Here, i will contain the index values
    print("".join(values[i]))

or

for i in values:  # Here, i will contain the sub_list
    print("".join(i))

Finally, if you follow the PEP-8 Python coding standards, you shouldn't use camelCase for variable names, so newValues should be new_values

Upvotes: 1

forin87
forin87

Reputation: 23

The .join hints into the right direction, but i is already the sub-list so you can do the following:

result = ["".join(i) for i in values] 
print(result)

Upvotes: 0

Related Questions