•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 427,942 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,593 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser: Programming Forums
You may want to call Python's list the answer to other computer languages' arrays. Here we take a look at the things you can do with lists, create an empty list, list the attributes and methods, load, append, count, insert, join, pop, remove, remove duplicate items, reverse, search, sort, establish a list of files, the list goes on ...
# experimenting with Python's list # tested with Python23 vegaseat 21feb2005 # import module os for method listdir() import os # creat an empty list (list object pointed to by iL) iL = [] print "\nThese are the attributes and methods of a list:" print dir(iL) print "\nA list of America's Most Popular Lawyers:" print iL print "\nLoad the list with 0 to 9" for number in range(10): iL.append(number) print "\nShow the loaded list:" print iL print "\nSame but simpler:" iL2 = range(10) print iL2 print "\nThere are %d elements, min = %d, max = %d" % (len(iL), min(iL), max(iL)) print "\nShow the first element (lists are zero based):" print iL[0] print "\nShow the final element:" print iL[-1] print "\nSum up all the integers in the list:" print sum(iL) # this is called slicing # [starting-at-index : but-less-than-index [ : step]] # start defaults to 0, end to len(sequence), step to 1 print "\nShow the first 3 elements:" print iL[:3] print "\nShow every second element starting with index 1:" print iL[1::2] # cloning, assign one list to another list from start to end iL2 = iL[:] # aliasing is simpler, but iL3 retains the address of iL # so if you change iL you also change iL3, oops!!! iL3 = iL print "\nList assigned to another list:" print "original", iL, "id =", id(iL) print "clone ", iL2, "id =", id(iL2) print "alias ", iL3, "id =", id(iL3) # search the list for integer 7 print "\nValue 7 is at index = %d\n" % iL.index(7) # insert an element print "Insert another 7 at that index:" iL.insert(iL.index(7),7) print iL # check if there are two sevens if iL.count(7) == 2 : print "There are two sevens in the list" elif iL.count(7) == 1 : print "There is one seven in the list" else: print "There are %d sevens in the list" % iL.count(7) print "\nRemove the extra 7 :" if iL.count(7) > 1 : iL.remove(7) print iL print "\nReverse the list:" iL.reverse() print iL print "\nSort the list:" iL.sort() print iL # insert a list list1 = ['a', 'b', 'c', 'd', 'e'] print "\nOriginal list:" print list1 print "Insert another list at index 3:" list1.insert(3, ['n1', 'n2', 'n3']) print list1 # ['a', 'b', 'c', ['n1', 'n2', 'n3'], 'd', 'e'] # using slicing to insert several elements into a list # this inserts elements of ['n1', 'n2', 'n3'] at index 3: list2 = ['a', 'b', 'c', 'd', 'e'] print "\nInsert elements of another list at index 3:" list2[3:3] = ['n1', 'n2', 'n3'] print list2 # ['a', 'b', 'c', 'n1', 'n2', 'n3', 'd', 'e'] # using slicing to replace an element with other elements # this replaces element at index 3 with elements of ['n1', 'n2', 'n3']: list3 = ['a', 'b', 'c', 'd', 'e'] print "\nReplace element at index 3 with elements of another list:" list3[3:4] = ['n1', 'n2', 'n3'] print list3 # ['a', 'b', 'c', 'n1', 'n2', 'n3', 'e'] # you can create a list of mixed types ... mixedList = [] mixedList.append(1.23) mixedList.append('a') mixedList.append('mixed') mixedList.append('type') mixedList.append('list') mixedList.append(77777) mixedList.append(0xff) # hex turns to decimal mixedList.append(355/113.0) # approximation of pi print "\nA list of mixed types:" print mixedList # show the difference between two lists using zip() and list comprehension list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] list2 = [1, 2, 3, 4, 4, 6, 7, 8, 9, 11] print "list1 =", list1 print "list2 =", list2 print '-' * 60 # vanity line of dashes print "These are the items different in the two lists:" print [(x, y) for (x, y) in zip(list1, list2) if x != y] # let's go from integers to strings ... print "\nOriginal string:" s = "I'm dreaming of a white precipitate" print s # create a list of strings print "\nSeparate string at any whitespace to a list of words:" sL = [] sL = s.split() print sL print "\nAdd 2 more words:" sL.append("in") sL.append("class") print sL # search the list for dreaming print "\n'dreaming' is at index = %d\n" % sL.index('dreaming') print "Insert an item at index 1 (moves rest of elements up):" sL.insert( 1, "merrily") print sL print "\nInsert an item one index in from the end:" sL.insert( -1, "chemistry") print sL print "\nPrint the list one item on a line:" # new line as delimiter print "\n".join(sL) print "\nJoin the list of words to form a string again:" # single space = " " as a delimiter s2 = " ".join(sL) print s2 print "\nRemove 'white' from the list:" sL.remove('white') print sL # treat this list like a stack (last in first out) # like a stack of dinner plates print "\nOperate the present list like a stack (LIFO):" print "pop last element = " + sL.pop() print "pop second last = " + sL.pop() print "pop third last = " + sL.pop() print "this is left:" print sL # treat this list like a queue (first in first out) # like the line at the store check-out print "Operate the present list like a queue (FIFO):" print "pop first element = " + sL.pop(0) print "pop second element = " + sL.pop(0) print "this is left:" print sL print "\nSort this list:" sL.sort() print sL print "\nIs 'of' in this list?" if 'of' in sL: print 'yes' # let's look at sorting a list of strings str = "I really love Monty Python's Flying Circus" wordList = [] wordList = str.split() print "\nThe original list of words:" print wordList print "\nSort this list (the default sort is case sensitive):" wordList.sort() print wordList # use anonymous function lambda to do a case insensitive sort # in this example compare as all lower case strings # (somewhat inefficient but sweet for short lists) print "\nHere is a sort that is case insensitive:" import string wordList.sort(lambda x, y: cmp(string.lower(x), string.lower(y))) print wordList # a way to weed out duplicate words from a list rawList = ['just', 'a', 'test', 'a', 'test', 'of', 'an', 'ordinary', 'string'] # create an empty list uniqueList = [] # use a list comprehension statement (takes a while to understand) [uniqueList.append(wrd) for wrd in rawList if not uniqueList.count(wrd)] print "The raw list containing duplicates:" print rawList print "The unique list (no duplicates):" print uniqueList # find all the .bmp files in the Windows folder print "\nAdd all the bitmap files in the Windows folder to a list:" path = 'c:/windows/' ext = '.bmp' # create an empty list fileList = [] for filename in os.listdir(path): if filename.endswith(ext): fileList.append(filename) # show the list of files print fileList print "\nShow one filename on each line:" for filename in fileList: print filename
Post Comment
•
•
•
•
DaniWeb Marketplace (Sponsored Links)