Q:

Python | Input comma separated elements, convert into list and print

0

Input comma separated elements (integers), and converts it into list in Python.

Example:

    Input:
    Enter comma separated integers: 10,20,30,40,50

    Output:
    list:  ['10', '20', '30', '40', '50']
    List (after converted each element to int)
    list (li) :  [10, 20, 30, 40, 50]

Logic:

  • Input a comma - separated string using raw_input() method.
  • Split the elements delimited by comma (,) and assign it to the list, to split string, use string.split() method.
  • The converted list will contains string elements.
  • Convert elements to exact integers:
    • Traverse each number in the list by using for...in loop.
    • Convert number (which is in string format) to the integer by using int() method.
  • Print the list.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

# input comma separated elements as string 
str = str (raw_input ("Enter comma separated integers: "))
print "Input string: ", str

# conver to the list
list = str.split (",")
print "list: ", list

# convert each element as integers
li = []
for i in list:
	li.append(int(i))

# print list as integers
print "list (li) : ", li

Output

    Enter comma separated integers: 10,20,30,40,50
    Input string:  10,20,30,40,50
    list:  ['10', '20', '30', '40', '50']
    list (li) :  [10, 20, 30, 40, 50]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now