My solution:
>>> i = 2
>>> list1 = []
>>> list1.append(i)
>>> list1
[2]
Is there a more elegant solution?
Typecasting to list can be done by simply using list(set_name) . Using sorted() function will convert the set into list in a defined order. The only drawback of this method is that the elements of the set need to be sortable.
With map and str We fast apply the str function to the given number. Then apply the in function repeatedly using map. Finally keep the result inside a list function.
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.
This is just a special case:
list1 = []
You can put the lists contents between the brackets. For example:
list1 = [i]
mylist = [i]
This will create a list called mylist with exactly one element i. This can be extended to create a list with as many values as you want: For example:
mylist = [i1,i2,i3,i4]
This creates a list with four element i1,i2,i3,i4 in that order. This is more efficient that appending each one of the elements to the list.
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