Posted By

chrisaiv on 08/25/09


Tagged

python


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

nerdfiles
louscomp
gartenstuhl


Python: List Basics


 / Published in: Python
 

How to concatenate lists, add an item to a list, slice an item from a list.

  1. #List #1
  2. inventory = ["sword", "armor", "shield", "healing potion"]
  3. #List #2
  4. chest = ["gold", "gems"]
  5.  
  6. #For Loop
  7. for item in inventory:
  8. print item
  9.  
  10. #Concatenating Lists
  11. inventory += chest
  12. print len(inventory)
  13.  
  14. #Adding New Items to the List
  15. inventory[4:4] = "chrisaiv"
  16.  
  17. #Assigning a New List Slice
  18. inventory[0:1] = ["rocks"]
  19. print inventory
  20.  
  21. #Delete a List Slice
  22. del inventory[4:9]
  23. print inventory

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: adkatrit on February 11, 2011

don't forget the other cool stuff you can do!

a=[1,2,3,4,5] a[::-1] [5,4,3,2,1] a[:] #copy you can do operations on without altering original [1,2,3,4,5] a[::2] [1,3,5] a[::3] [1,4] a[::-2] [5,3,1]

You need to login to post a comment.