Lists

Creating a list

list_name = ["item1", "item2", "item3"];

Call the 3rd item in the list

print "The first item is: " + list_name[2]

Replace item3 in the list

list_name[2] = "New_Value"

Append items to a list

list_name.append("New_item")

Find the index value of an item in the list

print list_name.index("item2")

Insert an item at index 1

list_name.insert(1, "New_Value")

Remove an item from a list

list_name.remove("item2")

Print the length of the list

print len(list_name)

Print only the first and second value of a list (slice)

print list_name[0:2]

Note: When slicing it includes all list items up to, but not including the last value
Sort items in a list

list_name.sort()

Dictionaries

A dictionary is similar to a list, but you access values by looking up a key instead of an index. A key can be any string or number. Dictionaries are enclosed in curly braces.
Define a dictionary

dictionary = {'key1' : 1, 'key2' : 2, 'key3' : 3}

Call the value of keypair 2

print dictionary['key2']

Add a value to dictionary

dictionary['key4'] = 4

Delete an item from a dictionary

del dictionary['key4']

Leave a Reply

Your email address will not be published. Required fields are marked *