This question already has answers here:
Converting a string representation of a list into an actual list object [duplicate]
(3 answers)
Closed 8 years ago.
I am pretty confused here.
I have a function that has a list as an argument. It then does list-specific functions on it. Here is an example:
def getValues( my_list ):
for q in my_list:
print(q)
But, I get my list from USER INPUT like this:
a_list = input("Please enter a list. ")
getValues(a_list)
The built-in input() function returns a string, not a list. My solution is to take that string of the list and turn it back into a list.
Only I don't know how.
Thanks!
Its what that ast.literal_eval is for :
>>> ast.literal_eval('[1,2,3]')
[1, 2, 3]
Related
This question already has answers here:
Getting a map() to return a list in Python 3.x
(11 answers)
Closed 2 years ago.
I am taking input from the user in single line string input. Trying to convert the input string into a list of numbers using the below-mentioned command:
This command returns a of type <map at 0x1f3759638c8>.
How to iterate or access this a?
Try simply doing the following -
a = list(map(int, input().split(' ')))
print(a)
> 5 4 3
[5, 4, 3]
You will get an error for the input that you have given i.e. 'Python is fun' because map will try to map the input to function int().
Let me explain:-
When you use input() , the input taken is in form of string.
Using split(' ') splits the string on every occurrence of space and a list will be created.
Value of that list will be ['Python','is','fun']
Now what map function does is, it applies int() on every element of the list. So basically what you are trying to do is int('Python'), which will give an error.
To avoid this use the following code snippet:
a = map(int, input().split(' '))
'1 2 3 4'
for i in a:
print(i)
Output of the above code will be
1
2
3
4
This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Closed 1 year ago.
Let's assume I have list, and have turned it into a string (to use it as a dictionary key for example). Is there a way to get the list back from the string? This code snippet should illustrate what I want:
list_str = str([1,2,3])
my_list = some_operation(list_str)
such that the variable my_list contains the list [1,2,3]
Any help would be appreciated!
You could use ast.literal_eval(list_str) but the real question is why did you convert it into a string in the first place? You could have converted it to a tuple (immutable and hashable) to use as a dict key
It's not a good idea, but you can try:
# list_str holds your list in a string
vals = list_str[1:-1]
l = [int(x.strip()) for x in vals.split(",")]
This question already has answers here:
How to convert list to string [duplicate]
(3 answers)
Closed 2 years ago.
Here is my list ['k:1','d:2','k:3','z:0'] now I want to remove apostrophes from list item and store it in the string form like 'k:1 , d:2, k:3, z:0' Here is my code
nlist = ['k:1','d:2','k:3','z:0']
newlist = []
for x in nlist:
kk = x.strip("'")
newlist.append(kk)
This code still give me the same thing
Just do this : print(', '.join(['k:1','d:2','k:3','z:0']))
if you want to see them without the apostrophes, try to print one of them alone.
try this:
print(nlist[0])
output: k:1
you can see that apostrophes because it's inside a list, when you call the value alone the text comes clean.
I would recommend studying more about strings, it's very fundamental to know how they work.
The parenthesis comes from the way of representing a list, to know wether an element is a string or not, quotes are used
print(['aStr', False, 5]) # ['aStr', False, 5]
To pass from ['k:1','d:2','k:3','z:0'] to k:1 , d:2, k:3, z:0 you need to join the elements.
values = ['k:1','d:2','k:3','z:0']
value = ", ".join(values)
print(value) # k:1, d:2, k:3, z:0
What you have is a list of strings and you want to join them into a single string.
This can be done with ", ".join(['k:1','d:2','k:3','z:0']).
This question already has answers here:
Convert all strings in a list to integers
(11 answers)
Closed 6 years ago.
Apologies if this question has already been covered!I am trying to convert each element in this list of listsinto integer format. I have used two for loops to iterate through the list, in the same way we do it "C" There is an error that says " Object is not subscriptable" in Line 3 . Am i missing something obvious?
Here is the code:
l=[['1','2'],['3','4']]
for i in range(len(l)):
for j in range(len[i]):
l[j]=int(l[j])
You can use nested list comprehensions:
outer = [['1','2'],['3','4']]
outer_as_ints = [[int(x) for x in inner] for inner in outer]
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
How can I ask from the user to enter a list in Python3,so as every time the program runs,the input list is the mutable data of the program?
For example, number lists,that user maybe enters are:
L1 = [7,9,16,25],L2 = [5,10,15,20],L3 = [10,17,19,24],`L4 = [16,20,20,23]
Please write the commensurable commands/statements.
python3's input() now always returns a string instead of evaluating the text as it did in python2.7. this means that you have to convert an input string into the type of data you need. a simple way of achieving this is to prompt the user to enter a list of numbers separated by commas. the resulting string can then be split into a list of strings by calling the string's .split() method. after converting to a list of strings, you can call int() or float() to convert each string into an individual number.
Example:
s = input("enter a list of numbers separated by commas:") #string
l = s.split(",") #list
n = [int(x) for x in l] #numbers