TutorialProgrammingPython

Interesting way to input lists on Python: Python list

List is one of the fundamental data types of Python. It runs a important role when it comes to coding. Today we are gong to discuss about lists in Python on this post.

Lists in python:

  • Python Lists are Mutable
  • Lists can contain strings, floats, and integers.
  • In Python, We can nest other lists, and we can also nest tuples and other data structures.
  • In python coding list we can perform slicing.

Input a list:

Inputting a list requires a lot of effort. If you want to simply use ‘input()’, we will get “str” that means string values, not list. 

At first we will test the code with ‘Input = [1,5,6,9,8,7]‘. Then will will test it with removing the squar brackets  ‘Input = 1,5,6,9,8,7′.

sample_list = input()
print(sample_list)
print(type(sample_list))

in this code if we type the input as below we will get such result. That is not expected. We want <class ‘list’>

input = [1,5,6,9,8,7]
output = [1,5,6,9,8,7]
         <class 'str'>

There are some possible solution for this problem. The 1st solution is we can use list( ) operation to convert the string type on list’s type.

sample_list = input()

sample_list2 = list(sample_list)
print(sample_list2)
print(type(sample_list2))
Input = [1,5,6,9,8,7]
output = 
['[', '1', ',', '5', ',', '6', ',', '9', ',', '8', ',', '7', ']']
<class 'list'>

We can see, we got out expected <class ‘list’>. But we failed to get the proper list we were searching. We expected [1,5,6,9,8,7] but got [‘[‘, ‘1’, ‘,’, ‘5’, ‘,’, ‘6’, ‘,’, ‘9’, ‘,’, ‘8’, ‘,’, ‘7’, ‘]’]

python list

So, what can we do!

lets test it with the second input, ‘Input = 1,5,6,9,8,7′

sample_list = input()

sample_list2 = list(sample_list)
print(sample_list2)
print(type(sample_list2))
Input=  1,5,6,9,8,7
Output= ['1,5,6,9,8,7']
       <class 'list'>

To solve this problem we will replace split() with split(‘,’), which means split operation will be done depending on comma( , ) . The function will find comma and will split the string upon this. Thus we get:

sample_list = input()
sample_list1 = sample_list.split(',')
print(sample_list1)
print(type(sample_list1))
Input= 1,5,6,9,8,7
Output= 
       ['1', '5', '6', '9', '8', '7']
       <class 'list'>

Now we got [‘1’, ‘5’, ‘6’, ‘9’, ‘8’, ‘7’], we have to solve this by applying a for loop. For loop will get the string elements, convert them into integer and then add in the new list. The code is below:

sample_list = input()
sample_list1 = sample_list.split(',')


new_list = []
for elements in sample_list1:
    element_int = int(elements)
    new_list.append(element_int)
print(new_list)
Input= 1,5,6,9,8,7
Output= [1, 5, 6, 9, 8, 7]
        <class 'list'>

30

Back to top button