Simple Tips for Collection in Python

  I believe that the following Python code is really not hard to understand. But I think we should use these tips

in our own code.

def main():
    #To judge whether a list is empty. We can use "if list0" instead of "if len(list0)". But we must be aware that [] is not None and [] is not False.
    list1 = [10, 12, 23, 24]
    list2 = []

    if list1:
        print "list1: {}".format(list1)
    else:
        print "list1 is an empty list: {}".format(list1)

    if list2:
        print "list2: {}".format(list2)
    else:
        print "list2 is an empty list: {}".format(list2)

    #[] is not None. [] is not False.
    print list2==None     #False
    print list2==False    #False
    print list2 is None   #False
    print list2 is False  #False

    #Get the index while traverse a list.
    for index, value in enumerate(list1):
        print "index: {}, value: {}".format(index, value)

if __name__ == '__main__':
    main()
else:
    print "Being imported as a module."

Output:

lxw Practice$ python collectionTips.py 
list1: [10, 12, 23, 24]
list2 is an empty list: []
False
False
False
False
index: 0, value: 10
index: 1, value: 12
index: 2, value: 23
index: 3, value: 24
lxw Practice$ 

  There are some other tips in this article.

 

Reference:

Python Collection小技巧:https://linuxtoy.org/archives/python-collection-tips.html

posted @ 2014-09-02 23:06  XiaoweiLiu  阅读(191)  评论(0编辑  收藏  举报