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

Here, we are going to learn how to convert comma separated elements into list using Python? Here, we will input comma separate elements and convert into a list of integers.
Submitted by IncludeHelp, on August 08, 2018

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 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.

Program

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

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

# convert each element as integer
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]

Python List Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.