Skip to content

Instantly share code, notes, and snippets.

@dhconnelly
Created March 29, 2012 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhconnelly/2236989 to your computer and use it in GitHub Desktop.
Save dhconnelly/2236989 to your computer and use it in GitHub Desktop.
lists tutorial for GSMST number theory
# sometimes we want to keep track of lots of things, without naming
# each one individually
# we want to read some names from the user
# what if we want to hold onto all of the names and do something with
# them later?
# for instance, we want to print them in reverse
names = [] # this is [ ]. this is called a LIST
while True:
name = raw_input('Enter a name: ')
if name == 'quit':
break
names.append(name) # this adds "name" to the end of the list "names"
print names
# if we want to get a specific element from the list, we can do:
print names[0] # this accesses the first element in the list
print names[2] # this accesses the 3rd element in the list
# how many elements are IN the list?
print len(names)
# we can reassign elements of the list:
names[1] = 13
print names
# we can delete items from a list
del names[1]
# this will remove the item in the 1 position AND SHIFT EVERYTHING DOWN
print names
# let's add another number
names.append(27)
print names
result = sorted(names)
print result
nums = [12, 5, 7, 18, 127, -1337]
print nums
print sorted(nums) # the sorted function DOES NOT modify the original list.
print nums # this will be the original list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment