1. 程式人生 > >python: data structure-list

python: data structure-list

  •  
  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered and unindexed. No duplicate members.
  • Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
  • In Python lists are written with square brackets.

 

  • to creat a list:
aList =['a','b','c']

>>> aList
['a','b','c']

>>> aList[0]
'a'

# or use list constructor list()

aList=list(('a','b','c'))
  • loop through a list; check if a list has a cerntain item:
aList =['a','b','c']
for cha in aList:
    print(cha)
if 'c' in aList:
    print("Yes")
  • length of a list: 
>>> len(aList)
3
  • add an item to the list:
>>> aList.append('d')
  • remove an item from the list:
>>> aList.remove('d')
  • remove an item at the specific index:
>>> del aList[0]

>>> del aList
  • remove the specific index item or the last item if the index is not specified:
>>> aList.pop(1)

>>> aList.pop()
  • empty a list:
>>> aList.clear

  • it's not recommended to use list for collecting different attributes of individual items, instead, for this case, tuple, named tuple, dictionaries and objects would be more suitable.
  • method sort() can be used to sort the elements in the list.
  • method __lt__ (lt: less than)