Python-Ref > Data structures > List > Adding items to a list
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Adding items to a list

To add items to a list, there are several ways. Probably the most often used one is the method append of the list object. It adds the item at the end of a list.
Expand/Shrink
Zdroj: (list3-1.py)
  1   xs = [1,2,3,4]
  2   print xs
  3   
  4   xs.append( 7)   # append the number 7
  5   print xs
  6   
  7   for i in range( 5):   # sequentially append all numbers between 0 and 4
  8       xs.append( i)
  9       print xs
 10   print xs
stdout:
[1, 2, 3, 4]
[1, 2, 3, 4, 7]
[1, 2, 3, 4, 7, 0]
[1, 2, 3, 4, 7, 0, 1]
[1, 2, 3, 4, 7, 0, 1, 2]
[1, 2, 3, 4, 7, 0, 1, 2, 3]
[1, 2, 3, 4, 7, 0, 1, 2, 3, 4]
[1, 2, 3, 4, 7, 0, 1, 2, 3, 4]
Doba běhu: 21.4 ms
To insert an item to a position different from the end of the list, the method insert is used.
Expand/Shrink
Zdroj: (list3-2.py)
  1   xs = [1,2,3,4]
  2   print xs
  3   
  4   xs.insert( 1, 100)   # insert the 100 to position 1
  5   print xs
  6   
  7   for i in range( 5):   # sequentially insert all numbers between 0 and 4
  8       xs.insert( i, i)  # the position where to insert 'i' is 'i'
  9       print xs
stdout:
[1, 2, 3, 4]
[1, 100, 2, 3, 4]
[0, 1, 100, 2, 3, 4]
[0, 1, 1, 100, 2, 3, 4]
[0, 1, 2, 1, 100, 2, 3, 4]
[0, 1, 2, 3, 1, 100, 2, 3, 4]
[0, 1, 2, 3, 4, 1, 100, 2, 3, 4]
Doba běhu: 21.1 ms