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

65,042

Solution 1

This is just a special case:

list1 = []

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

list1 = [i]

Solution 2

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.

Solution 3

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

Share:
65,042

Related videos on Youtube

latgarf
Author by

latgarf

Updated on November 10, 2020

Comments

  • latgarf
    latgarf over 3 years

    My solution:

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

    Is there a more elegant solution?

    • information_interchange
      information_interchange over 4 years
      list(i) doesn't work. Does anyone know the reasoning behind this?
  • Mike Housky
    Mike Housky about 9 years
    That trailing comma only works with tuples, like (2,), and only because (2) would be considered an integer expression, not a tuple. [2,] is a syntax error.
  • LinkBerest
    LinkBerest about 9 years
    @MikeHousky try it, python 2 it works fine. Also just tested in Python 3 and it still works.
  • Mike Housky
    Mike Housky about 9 years
    Odd. I did try it (Python 2.7.8) and got the syntax error. Trying again after your response, though, it worked!? Idle must have hiccuped. I learned something today. (Not sure I'll ever use it, though.)
  • Jerry T
    Jerry T over 7 years
    yea, it is even more confusing when one switches between python, R, matlab from time to time. it might be a good habit to always remember to add , to the single element whenever possible.
  • hpaulj
    hpaulj over 3 years
    tup1 = 2, makes a single element tuple. The () are optional.