# How to assign integers to another variable as a list? (Python 3)?

I'm learning Python and have looked this up on various websites and haven't found anything.

I have variables A and B.

Variable A's assigned value is a series of integers.

A = 3 9 5 2

I need to turn these into a list, and assign them to variable B, so that

B = [3, 9, 5, 2]

hopefully someone can explain it simply to me, i'm new to python and can't find any solutions to this online.

Relevance
• 8 months ago

If you want to convert a string with a text representation of a variable number of integers, separated by spaces and/or tabs, then you can use a "list comprehension", in conjunction with the string .split() method (mentioned in another answer.)  Try this at the Idle or interactive Python prompt:

text = '1 1 2 3 5 8 13 21 34'

fib = [int(s) for s in text.split()]

print(fib)

That about as easy as it gets.  You could also use a loop:

fib = []

for s in text.split():

fib.append(int(s))

...which does the same thing, but in 3 lines instead of 1.

• EddieJ
Lv 7
8 months ago

Variable A cannot simply be a series of integers, however, maybe you mean that it is a string, which could obtain that value from the input () function, which would get the numbers from the user (entered on the keyboard), or it could be hard-coded in the program as

A = "3 9 5 2"

So, you would just have

B = A.split ()