Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a single number into a single item list in python

My solution:

>>> i = 2
>>> list1 = []
>>> list1.append(i)
>>> list1
[2]

Is there a more elegant solution?

like image 640
latgarf Avatar asked Apr 13 '15 04:04

latgarf


People also ask

How do you convert a set of numbers to a list in Python?

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.

How do you convert one integer to a list in Python?

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.

How do you convert an item to a list in Python?

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.


2 Answers

This is just a special case:

list1 = []

You can put the lists contents between the brackets. For example:

list1 = [i]
like image 149
John1024 Avatar answered Nov 02 '22 04:11

John1024


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.

like image 20
Hadi Khan Avatar answered Nov 02 '22 05:11

Hadi Khan