Most newbies to Python find this fascinating. Converting a list of elements to a long string requires only one line of code.
Here’s an example.
Suppose we have a list of names, and we need to convert it into a string. We also want each element separated by a comma. The following code will do the trick.
In the above example, we use the join method of any string to convert a list. Instead of a comma, we can give any text. As we change it, you’ll notice that the connecting part between any two-element is different. Instead of a comma, we can provide any text.
Converting a list of numbers to a string
The join method works fine for a list of strings. Yet, if the list comprises numbers, it throws an error.
Another little Python trick in such a situation is to use comprehension. Comprehensions are a convenient way to loop through elements without writing multi-line statements.
Here, in the following example, we convert each element in the list to a string and then use the join method as before. We can see the list is now converting to text without any error.
Conditionally select elements before joining.
Often we don’t want to join every element of a list. We may wish to select a few based on some conditions. We can extend the list comprehension to include such situations to tackle this.
Suppose, in addition to converting numbers to strings, we might want to include only odd numbers in our join operation. The following code will do it.
In the above example, we used the
el%2==1 condition to include only elements that meet this condition. That is to have only odd numbers.
Transform list elements and join them to create a string.
We need to apply some complex transformations to the elements in some instances before joining them. The change could be anything.
The following list has both strings and numbers in the list in the following example. We need to use the texts as it is. But for numbers, without directly converting them into a string, we need to use it’s literal. We do it by looking it up into a dictionary.
Let’s create a small function that does the lookup.
We can use this function to convert the elements as we did with
str. But there’s a better method to do this. Use map functions when you have complex logic to apply to a list.
In the above example, we used the map function to apply the number_lookup to our list before joining them. When the transformation is complex, it’s always better to use the map function instead of list comprehension.
Not a Medium member yet? Please use this link to become a member because I earn a commission for referring at no extra cost for you.