User Name Password Register
DaniWeb IT Discussion Community
All
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
Feb 21st, 2005
Views: 28,279
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 ...
python Syntax | 5 stars
  1. # experimenting with Python's list
  2. # tested with Python23 vegaseat 21feb2005
  3.  
  4. # import module os for method listdir()
  5. import os
  6.  
  7. # creat an empty list (list object pointed to by iL)
  8. iL = []
  9.  
  10. print "\nThese are the attributes and methods of a list:"
  11. print dir(iL)
  12.  
  13. print "\nA list of America's Most Popular Lawyers:"
  14. print iL
  15.  
  16. print "\nLoad the list with 0 to 9"
  17. for number in range(10):
  18. iL.append(number)
  19.  
  20. print "\nShow the loaded list:"
  21. print iL
  22.  
  23. print "\nSame but simpler:"
  24. iL2 = range(10)
  25. print iL2
  26.  
  27. print "\nThere are %d elements, min = %d, max = %d" % (len(iL), min(iL), max(iL))
  28.  
  29. print "\nShow the first element (lists are zero based):"
  30. print iL[0]
  31.  
  32. print "\nShow the final element:"
  33. print iL[-1]
  34.  
  35. print "\nSum up all the integers in the list:"
  36. print sum(iL)
  37.  
  38. # this is called slicing
  39. # [starting-at-index : but-less-than-index [ : step]]
  40. # start defaults to 0, end to len(sequence), step to 1
  41. print "\nShow the first 3 elements:"
  42. print iL[:3]
  43. print "\nShow every second element starting with index 1:"
  44. print iL[1::2]
  45. # cloning, assign one list to another list from start to end
  46. iL2 = iL[:]
  47. # aliasing is simpler, but iL3 retains the address of iL
  48. # so if you change iL you also change iL3, oops!!!
  49. iL3 = iL
  50. print "\nList assigned to another list:"
  51. print "original", iL, "id =", id(iL)
  52. print "clone ", iL2, "id =", id(iL2)
  53. print "alias ", iL3, "id =", id(iL3)
  54.  
  55. # search the list for integer 7
  56. print "\nValue 7 is at index = %d\n" % iL.index(7)
  57.  
  58. # insert an element
  59. print "Insert another 7 at that index:"
  60. iL.insert(iL.index(7),7)
  61. print iL
  62. print
  63.  
  64. # check if there are two sevens
  65. if iL.count(7) == 2 :
  66. print "There are two sevens in the list"
  67. elif iL.count(7) == 1 :
  68. print "There is one seven in the list"
  69. else:
  70. print "There are %d sevens in the list" % iL.count(7)
  71.  
  72. print "\nRemove the extra 7 :"
  73. if iL.count(7) > 1 :
  74. iL.remove(7)
  75. print iL
  76.  
  77. print "\nReverse the list:"
  78. iL.reverse()
  79. print iL
  80.  
  81. print "\nSort the list:"
  82. iL.sort()
  83. print iL
  84.  
  85. # insert a list
  86. list1 = ['a', 'b', 'c', 'd', 'e']
  87. print "\nOriginal list:"
  88. print list1
  89. print "Insert another list at index 3:"
  90. list1.insert(3, ['n1', 'n2', 'n3'])
  91. print list1 # ['a', 'b', 'c', ['n1', 'n2', 'n3'], 'd', 'e']
  92.  
  93. # using slicing to insert several elements into a list
  94. # this inserts elements of ['n1', 'n2', 'n3'] at index 3:
  95. list2 = ['a', 'b', 'c', 'd', 'e']
  96. print "\nInsert elements of another list at index 3:"
  97. list2[3:3] = ['n1', 'n2', 'n3']
  98. print list2 # ['a', 'b', 'c', 'n1', 'n2', 'n3', 'd', 'e']
  99.  
  100. # using slicing to replace an element with other elements
  101. # this replaces element at index 3 with elements of ['n1', 'n2', 'n3']:
  102. list3 = ['a', 'b', 'c', 'd', 'e']
  103. print "\nReplace element at index 3 with elements of another list:"
  104. list3[3:4] = ['n1', 'n2', 'n3']
  105. print list3 # ['a', 'b', 'c', 'n1', 'n2', 'n3', 'e']
  106.  
  107. # you can create a list of mixed types ...
  108. mixedList = []
  109. mixedList.append(1.23)
  110. mixedList.append('a')
  111. mixedList.append('mixed')
  112. mixedList.append('type')
  113. mixedList.append('list')
  114. mixedList.append(77777)
  115. mixedList.append(0xff) # hex turns to decimal
  116. mixedList.append(355/113.0) # approximation of pi
  117. print "\nA list of mixed types:"
  118. print mixedList
  119.  
  120. print
  121.  
  122. # show the difference between two lists using zip() and list comprehension
  123. list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  124. list2 = [1, 2, 3, 4, 4, 6, 7, 8, 9, 11]
  125. print "list1 =", list1
  126. print "list2 =", list2
  127. print '-' * 60 # vanity line of dashes
  128. print "These are the items different in the two lists:"
  129. print [(x, y) for (x, y) in zip(list1, list2) if x != y]
  130.  
  131. # let's go from integers to strings ...
  132. print "\nOriginal string:"
  133. s = "I'm dreaming of a white precipitate"
  134. print s
  135.  
  136. # create a list of strings
  137. print "\nSeparate string at any whitespace to a list of words:"
  138. sL = []
  139. sL = s.split()
  140. print sL
  141.  
  142. print "\nAdd 2 more words:"
  143. sL.append("in")
  144. sL.append("class")
  145. print sL
  146.  
  147. # search the list for dreaming
  148. print "\n'dreaming' is at index = %d\n" % sL.index('dreaming')
  149.  
  150. print "Insert an item at index 1 (moves rest of elements up):"
  151. sL.insert( 1, "merrily")
  152. print sL
  153.  
  154. print "\nInsert an item one index in from the end:"
  155. sL.insert( -1, "chemistry")
  156. print sL
  157.  
  158. print "\nPrint the list one item on a line:"
  159. # new line as delimiter
  160. print "\n".join(sL)
  161.  
  162. print "\nJoin the list of words to form a string again:"
  163. # single space = " " as a delimiter
  164. s2 = " ".join(sL)
  165. print s2
  166.  
  167. print "\nRemove 'white' from the list:"
  168. sL.remove('white')
  169. print sL
  170.  
  171. # treat this list like a stack (last in first out)
  172. # like a stack of dinner plates
  173. print "\nOperate the present list like a stack (LIFO):"
  174. print "pop last element = " + sL.pop()
  175. print "pop second last = " + sL.pop()
  176. print "pop third last = " + sL.pop()
  177. print "this is left:"
  178. print sL
  179. print
  180.  
  181. # treat this list like a queue (first in first out)
  182. # like the line at the store check-out
  183. print "Operate the present list like a queue (FIFO):"
  184. print "pop first element = " + sL.pop(0)
  185. print "pop second element = " + sL.pop(0)
  186. print "this is left:"
  187. print sL
  188.  
  189. print "\nSort this list:"
  190. sL.sort()
  191. print sL
  192.  
  193. print "\nIs 'of' in this list?"
  194. if 'of' in sL:
  195. print 'yes'
  196.  
  197. # let's look at sorting a list of strings
  198. str = "I really love Monty Python's Flying Circus"
  199. wordList = []
  200. wordList = str.split()
  201. print "\nThe original list of words:"
  202. print wordList
  203. print "\nSort this list (the default sort is case sensitive):"
  204. wordList.sort()
  205. print wordList
  206. # use anonymous function lambda to do a case insensitive sort
  207. # in this example compare as all lower case strings
  208. # (somewhat inefficient but sweet for short lists)
  209. print "\nHere is a sort that is case insensitive:"
  210. import string
  211. wordList.sort(lambda x, y: cmp(string.lower(x), string.lower(y)))
  212. print wordList
  213.  
  214. print
  215.  
  216. # a way to weed out duplicate words from a list
  217. rawList = ['just', 'a', 'test', 'a', 'test', 'of', 'an', 'ordinary', 'string']
  218. # create an empty list
  219. uniqueList = []
  220. # use a list comprehension statement (takes a while to understand)
  221. [uniqueList.append(wrd) for wrd in rawList if not uniqueList.count(wrd)]
  222. print "The raw list containing duplicates:"
  223. print rawList
  224. print "The unique list (no duplicates):"
  225. print uniqueList
  226.  
  227. # find all the .bmp files in the Windows folder
  228. print "\nAdd all the bitmap files in the Windows folder to a list:"
  229. path = 'c:/windows/'
  230. ext = '.bmp'
  231. # create an empty list
  232. fileList = []
  233. for filename in os.listdir(path):
  234. if filename.endswith(ext):
  235. fileList.append(filename)
  236.  
  237. # show the list of files
  238. print fileList
  239.  
  240. print "\nShow one filename on each line:"
  241. for filename in fileList:
  242. print filename
Post Comment

Only community members can submit or comment on code snippets. You must register or log in to contribute.

DaniWeb Marketplace (Sponsored Links)
All times are GMT -4. The time now is 6:50 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC