Python: Lists, Tuples and Dictionaries


Lists, Tuples and Dictionaries

Many programming languages have an array data structure that allows you to store multiple items grouped together as a name with the items available by referecning the index value of the item in the array. For example, you could create an array called scores that stores a set of bowling scores. The use of arrays adds many advantaages to how the data in it can be accessed and used, e.g. count, total, average, change, etc.

Python does not use arrays, but uses data structures it refers to as lists, tuples, and dictionaries that are very siumiliar. Below is a description of each.

  • Lists - a list of values. Each one of them is numbered, starting from zero. The first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. E.g. list of employee names, list of bowling scores, etc.
  • Tuples - tuples are just like lists, but you can't change their values. Like a list, each value is numbered starting from zero. E.g.: the names of the months of the year.
  • Dictionaries - dictionaries are similar to what some languages refer to as an associate array. The values in a dictionary aren't numbered. You have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. You can add, remove, and modify the values in dictionaries.

List Examples


Example: Creating and Simple Outputting of List Data


	cats = ['Simon', 'Baxter', 'Tiger', 'Kitty', 'Felix']
	print(cats)
	print(cats[2])
	

Output:

  ['Simon', 'Baxter', 'Tiger', 'Kitty', 'Felix']
  Tiger


Example: Creating Lists and Adding Elements to a list


	scores=[90,91,92,93]
	print(scores)
	scores.append(50)
	print(scores)
	scores.insert(1,100)
	print(scores)
	scores2=(30,30)
	scores.extend(scores2)
	print(scores)
	

Output:

  [90, 91, 92, 93]
  [90, 91, 92, 93, 50]
  [90, 100, 91, 92, 93, 50]
  [90, 100, 91, 92, 93, 50, 30, 30]


Example: Inserting a new element at a specific location in a list


	cats = ['Simon', 'Baxter', 'Tiger', 'Kitty', 'Felix']
	cats.insert(1, 'Dusty')
	print(cats)
	

Output:

  ['Simon', 'Dusty', 'Baxter', 'Tiger', 'Kitty', 'Felix']


Example: Inserting a new element from user input in a list and counting elements


	cats = ['Simon', 'Baxter', 'Tiger', 'Kitty', 'Felix']

	cat = input("Please enter a new cat: ")
	cats.append(cat)

	print("You now have", len(cats), "cats.")

	print(cats)
	

Output:

  Please enter a new cat: Goucho
  You now have 6 cats.
  ['Simon', 'Baxter', 'Tiger', 'Kitty', 'Felix', 'Goucho']


Example: Outputting list data with For Loops


	cats = ['Simon', 'Baxter', 'Tiger', 'Kitty', 'Felix']
	for cat in cats:
		print("Cat: ", cat)
	print("")
	for i in range(0, len(cats)):
		cat = cats[i - 1]
		print(i+1, cat)
	

Output:

  Cat: Simon
  Cat: Baxter
  Cat: Tiger
  Cat: Kitty
  Cat: Felix

  1 Felix
  2 Simon
  3 Baxter
  4 Tiger
  5 Kitty


Example: Outputting list with a while loop


	cats = ['Simon', 'Baxter', 'Tiger', 'Kitty', 'Felix']
	i=0
	while i < len(cats):
		print("Cat name: ", cats[i])
		i+=1
	

Output:

  Cat name: Simon
  Cat name: Baxter
  Cat name: Tiger
  Cat name: Kitty
  Cat name: Felix


Example: Sorting a list


	cats = ['Simon', 'Baxter', 'Tiger', 'Kitty', 'Felix']
	cats.sort()
	print(cats)
	

Output:

  ['Baxter', 'Felix', 'Kitty', 'Simon', 'Tiger']


Example: Counting number of specific items in a list


	name="Tiger"
	cats = ['Simon', 'Baxter', 'Tiger', 'Kitty', 'Tiger', 'Felix']
	number = cats.count(name)
	print("Number of cats named", name, "is", number)
	

Output:

  Number of cats named Tiger is 2


Example: Finding matches in a list


	foods = ["Cheesecake","Steak","Donuts","Apples","Bread","Lettuce","Cottage cheese", "Pears"]
	choice = input("Enter food to search for: ")
	if choice in foods:
		print("We have that food in stock.")
	else:
		print("We do not have that food in stock.")
	

Example: removing items, looping through, searching for certain items (one dimensional)


	scores=[90,85,73,94,85,88]
	print ("Scores: ", scores)
	scores += [97]   # add an item to end
	print ("Scores: ", scores)
	scores.remove(85)  # remove first instance of 85
	scores.remove(85)  # remove next instance of 85
	print ("Scores: ", scores)
	i = 0
	count = len(scores)
	while i < count:
		if scores[i] >=90:
			print ("Scores:", scores[i])
		i+=1
	scores2 = [i for i in scores if i >= 90] # create new list containing only scores >= 90
	print ("Scores: ", scores2)
	average = sum(scores) / float(len(scores))
	print ("Average: ", average)
	

Output:

  Scores: [90, 85, 73, 94, 85, 88]
  Scores: [90, 85, 73, 94, 85, 88, 97]
  Scores: [90, 73, 94, 88, 97]
  Scores: 90
  Scores: 94
  Scores: 97
  Scores: [90, 94, 97]
  Average: 88.4


Example: Two dimensional list


	quiz1=[["Bob Smith",92],["Mary Jones",94],["John Taylor",84]]
	print ("Student #1: ", quiz1[0])

	count = len(quiz1)
	for x in range(0, count):
		print ("Student #", x+1, quiz1[x])

	print ("Student #1 score:", quiz1[0][1])
	for x in range(0, count):
		print ("Student #", x+1, "\t Name:", quiz1[x][0], "\t Score:", quiz1[x][1])
	

Output:

  Student #1: ['Bob Smith', 92]
  Student # 1 ['Bob Smith', 92]
  Student # 2 ['Mary Jones', 94]
  Student # 3 ['John Taylor', 84]
  Student #1 score: 92
  Student # 1 Name: Bob Smith Score: 92
  Student # 2 Name: Mary Jones Score: 94
  Student # 3 Name: John Taylor Score: 84


Example: Two dimensional list


	employees = [
		[12334, 'Jane Smith', 'Supervisor'],
		[23434, 'Patty Johnson', 'Director'],
		[33244, 'Kevin Furlough', 'Manager']
	]
	for x in range(3):
		if len(employees[x][1]) < 14:
			print(employees[x][0], "\t\t", employees[x][1], "\t\t\t", employees[x][2])
		else:
			print(employees[x][0], "\t\t", employees[x][1], "\t\t", employees[x][2])
	

Output:

  12334      Jane Smith            Supervisor
  23434      Patty Johnson      Director
  33244      Kevin Furlough     Manager


Tuple Examples


Example: A tuple of months


	months = ('January','February','March','April','May','June',\
	'July','August','September','October','November','  December')

	print (months)
	print (months[1])
	

Output:

  ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', ' December')
  February


Example: Tuple example

In the example below, an error occurs when the program is run because the same sort attribute/function used with a list is not available for a tuple.


	months = ('January','February','March','April','May','June',\
		'July','August','September','October','November','  December')
	months.sort()
	

Output:

  Traceback (most recent call last):
        File "C:/test.py", line 3, in
                months.sort()
    AttributeError: 'tuple' object has no attribute 'sort'