J. Wash
J. Wash

Reputation: 7

How to add each number to list in python?

I have following variable:

number = "456367"

I need to add it to list by one number, like this:

list = [['4', '5', '6', '3', '6', '7']]

How can I achieve this?

Upvotes: 0

Views: 78

Answers (2)

dawg
dawg

Reputation: 104092

Since a string is iterable, pass it to the list constructor:

>>> list("456367")
['4', '5', '6', '3', '6', '7']

Which is why you would not want to name the result list because you would stomp on the name of that convenient function ;-)


If you really want [['4', '5', '6', '3', '6', '7']] vs just a list of characters:

>>> s="456367"
>>> map(list, zip(*s))
[['4', '5', '6', '3', '6', '7']]

Or,

>>> [list(s)]
[['4', '5', '6', '3', '6', '7']]

But I am assuming with the first answer that the extra brackets were a typo.

Upvotes: 1

jakevdp
jakevdp

Reputation: 86473

>>> number = "456367"
>>> [char for char in number]
['4', '5', '6', '3', '6', '7']

Upvotes: 0

Related Questions