Skip to content

Instantly share code, notes, and snippets.

@gergob
Last active August 29, 2015 14:11
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 gergob/058c5ad42f04e7169679 to your computer and use it in GitHub Desktop.
Save gergob/058c5ad42f04e7169679 to your computer and use it in GitHub Desktop.
my_list_1 = [1, 3, 5, 7, 11, 13, 17]
my_list_2 = range(10, 21) # will result [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
my_list_3 = range(10)
for nr in my_list_3:
print(nr)
# and maybe do some other stuff
#indexing - used for getting and setting values
a = [17, 19, 23, 29]
print(a[0]) # will print 17
print(a[2]) # will print 23
a[1] = 1001 # update the second item to 1001
print(a[1]) # will print 1001
#append
my_list_4 = ["hello", 1, "world", "John", 2, 3, 4, 5, "Doe"]
my_list_4.append([6, 7, 8]) # my_list_4 will be ["hello", 1, "world", "John", 2, 3, 4, 5, "Doe", [6, 7, 8]]
my_list_4.append("Australia") # my_list_4 will be ["hello", 1, "world", "John", 2, 3, 4, 5, "Doe", [6, 7, 8], "Australia"]
#adding and extending
my_list_5 = [10, 100, 1000]
my_list_6 = ["ten", "hundred", "thousand"]
my_list_7 = my_list_5 + my_list_6 # my_list_7 will be [10, 100, 1000, "ten", "hundred", "thousand"]
my_list_8 = [9, 8, 7]
my_list_9 = [6, 5, 4, 3, 2, 1]
my_list_8.extend(my_list_9) # my_list_8 will be [9, 8, 7, 6, 5, 4, 3, 2, 1]
#insert - adding item(s) to a specific position within a list
my_list = [2, 5, 6, 7]
my_list.insert(0, 1) # will insert the 1 at the 0th position
my_list.insert(2, 3) # will insert the 3 at the 2nd position
my_list.insert(3, 4) # will insert the 4 at the 3th position
#pop - removes(pops out) the last item in the list
my_list = [1, 2, 3]
my_list.pop() # will remove and return the value 3
print(my_list) # will display [1, 2]
#remove - removes ONLY the first the value passed in as parameter from the list
my_list = [4, 5, 6, 7, 4, 6]
my_list.remove(6) # will only remove the 6 on the 2nd position
print(my_list) # will display [4, 5, 7, 4, 6]
#len, sort and reverse methods
print(len(my_list)) # will print 5
my_list.sort()
print(my_list) # will display [4, 4, 5, 6, 7]
my_list.reverse()
print(my_list) # will display [7, 6, 5, 4, 4]
#del - deleting an item from the list
c = [55, 75, 85, 105]
del c[2] # will delete the list item on 2nd position
print(c) # will display [55, 75, 105]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment