Reputation: 511
My solution:
>>> i = 2
>>> list1 = []
>>> list1.append(i)
>>> list1
[2]
Is there a more elegant solution?
Upvotes: 32
Views: 100398
Reputation: 331
As it has already been said, you can write for a single value
list1 = [i]
This is a "0th order" list comprehension which turns out to be a relevant and powerful python tool.
Check https://docs.python.org/2/tutorial/datastructures.html
Upvotes: 0
Reputation: 587
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.
Upvotes: 11
Reputation: 1311
is it just a single assignment or is this within another construct? if just an assignment:
list1 = [2,] #This is equivalent to list1 = [2], I add the comma out of habit (but either works)
#if construct it depends but this assigns the variable as the list element
list1 = [i] #is fine
Upvotes: 1
Reputation: 1477
To place something inside of a list, simply wrap it in brackets, like so:
i = 4
print( [i] )
or
iList = [i]
print( iList )
Run a working example here http://www.codeskulptor.org/#user39_XH1ahy3yu5b6iG0.py
Upvotes: 4
Reputation: 113824
This is just a special case:
list1 = []
You can put the lists contents between the brackets. For example:
list1 = [i]
Upvotes: 32