Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I wrote the code for the counter in python, but I did not my appropriate result. I made the list by input numbers,then wanted to make a counter and send the result of the counter in a new list and print it: How can I do that?

`>>>num1=int(input("plz enter a number: "))

 >>>num2=int(input("plz enter a number: "))

 >>>num3=int(input("plz enter a number: ")) 

 >>>list1= [num1,num2,num3] 

 >>>for n in list1:

 >>> n=n+1

 >>> print(n)`

the result after input numbers would be:

plz enter a number: 32

plz enter a number: 15

plz enter a number: 18

33

16

19

but I want to see 33,16,19 in a list. like:

[33,16,19]

1 Answer

0 votes
by (36.8k points)
edited by

The idiomatic way to create the new list in Python is called the comprehension:

list2 = [i+1 for i in list1]

It is almost equivalent but shorter and more efficient (we say more pythonic) than:

list2 = []

for i in list1:

    list2.append(i+1)

If you are a beginner and want to know more about Python the do check out the Python for Data Science

Browse Categories

...