0

When I create list as

a=[5,6,8,7]; print(a)

it shows output as

[5, 6, 8, 7]

and when take input as

b=list(input());print(b) 

it shows output as

['5', '6', '7', '8']

why and what is difference in that. I can add 5 and 6 as 11 but in second adding 5 and 6 is 56 ?

ForceBru
  • 43,482
  • 10
  • 63
  • 98

2 Answers2

1

It's because input() returns a string and + is thus doing string concatenation. From the input() documentation:

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

TomNash
  • 3,147
  • 2
  • 21
  • 57
0

input() returns a string, list(input()) extracts its individual characters and puts them in a list. Adding individual characters, which are strings of one character, produces a new string:

'5' + '6' == '56'
5 + 6 == 11

To convert a list of strings to a list of integers, use map:

integers = list(map(int, input()))
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • "Use map"...or use [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions): `integers = [int(c) for c in input()]` – Leporello Jun 14 '19 at 12:36