Home > OS >  How to convert a string into a list in Python?
How to convert a string into a list in Python?

Time:10-16

How can I convert a variable with the value 10, like this variable = "10" , into a list from 10 to 0 like this:

list = ["10", "9", "8", "7", "6", "5", "4", "3", "2", "1","0",]

CodePudding user response:

Another solution (that skips [::-1]):

variable = "10"

out = list(map(str, range(int(variable), -1, -1)))
print(out)

Prints:

['10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0']

CodePudding user response:

You can also use a list comprehension. First convert the string to int.

print([str(i) for i in range(int('10'),-1,-1)])
# Which prints
['10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0']

CodePudding user response:

Try this:

# 1: Contvert str '10' to int.
# 2: Create range(10 1) -> [0,...10]
# 3: Reverse list to desired order with '[::-1]' -> [10, 9, ..., 0]
# 4: Convert all elements in 'list' to 'str' with 'map(str, ...)'
>>> list(map(str, range(int('10') 1)[::-1]))
['10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0']

CodePudding user response:

Try using map and __reversed__:

variable = "10"
print(list(map(str, range(int(variable) 1).__reversed__())))

Or "slower" ones using sorted:

variable = "10"
print([str(x) for x in sorted(range(int(variable) 1), reverse=True)])
  • Related