Lists are similar to arrays and in Python, it is quite easy to build them. Here is a simple program that adds a list of numbers using the built-in function sum.
mylist = [1,2,3]
print 'sum of the list is',sum(mylist)
Sometimes we may wish to take certain items from a list and use them for a certain purpose, for example item 1 minus item 3 or adding the first two items of a list .
mylist = [1,2,3]
print 'sum of the list is',sum(mylist)
print
print 'item 1 minus item 3 of the list is ',mylist[0] - mylist[2]
print 'sum of first two items of the list is ' ,sum(mylist[0:2])
No comments:
Post a Comment