Python Containers: Lists vs Dictionaries

Python has many different containers available, here we'll cover a couple of them
Containers are objects “which contain references to other objects instead of data” and are used to group related variables together (3.2)
There are many types of containers to include:
  • lists
  • dictionaries
  • tuples
  • and more…
Lists
Lists are Python’s version of arrays and are declared using square brackets []. Lists are ordered sequences that can hold a variety of object types (not limited to a single type). For instance,
my_list = [‘one’, 2, 3.0]]
holds a string, an int, and a float.
Lists support indexing, where elements are accessed by their sequential order, starting from 0. In the above example:
  • my_list[0] holds a value of ‘one’
  • my_list[1] holds a value of 2
  • my_list[2] holds a value of 3.0
Objects in a list can also be referenced from right to left:
  • my_list[0] holds a value of ‘one’
  • my_list[-1] holds a value of 3.0
  • my_list[-2] holds a value of 2
Slicing
Lists also support slicing, which is sort of like an expanded capability of indexing. The syntax for slicing is:
object_to_be_sliced[start:stop:step]
Like slicing with strings, slicing of list enables you to grab a subsection of the sequential objects using indexes.
Example:
my_nums = [0,1,2,3,4,5,6,7,8,9,10]
print(my_nums[0:6])
>> [0,1,2,3,4]  
#Note that this goes up to but does not include the stop index
print(my_nums[0::2])
>>[0,2,4,6,8,10]
#Step is hoe many indexes are skipped with each iteration

print(my_nums[::-1])
>> [10,9,8,7,6,5,4,3,2,1,0]
#Using only a step value of -1 returns the list reversed 
print(my_nums[0:10:3])
>> [0,3,6,9]

Dictionaries:
In contrast to list, dictionaries are unordered mappings for storing objects. Dictionaries store objects in key-value pairs wherein the key is a string which is used to retrieve its associated value.
Consider a dictionary of object – price key-value pairs:
menu_prices = {‘cheesburger’:2.99, ‘dbl_cheeseburger’: 3.99,’bacon_cheeserburger’: 3.49, ‘bacon_dbl_cheeseburger’: 4.49}
menu_prices[‘bacon_cheeseburger’]
>> 3.49

Unlike lists, dictionaries do not support indexing or slicing, which is really the deciding factor in whether to use a list or a dictionary. It comes down to whether you need/intend to use indexing/slicing.
Like lists, dictionaries can contain multiple object types simultaneously, to include nested dictionaries and nested lists. 
Both lists and dictionaries are mutable, meaning the values can be changed. 

0 Comments:

Post a Comment