I have a string which I want to convert to a list with only one element in it.
a = abc
print list(a)
output : ['a','b','c']
Expected o/p = ['abc']
What is the proper way to do it ?
Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
Using the * Operator The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list. Here, we just have to keep in mind that to repeat the elements n times, we will have to multiply the list by (n+1).
In Python, a list is created by placing elements inside square brackets [] , separated by commas.
Simply use [..]
:
a = 'abc'
b = [a]
print(b)
[..]
is list notation, you can feed it a comma-separated list of values. For instance [1,4,2,5,'a',1+2,4/3,3.1415]
,... Or as specified in the documentation:
(..) The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With