Python Data Structures

A data structure is a container that organize data in a specific layout. Any data structure is plan to arrange data to suit a certain purpose so that it can be accessed and worked with in suitable ways. Python has the following built-in data structures:

  1. List (Mutable Arrays)
  2. Tuple (Immutable Arrays)
  3. Dictionary (Hashtables)
  4. Sets

List

List (Mutable Arrays) in Python is one of the most frequently used and very versatile data structure. Python Lists are mutable, this means that the list elements can be changed unlike string or tuple. It can be created using square brackets[] and allows duplicate members.


Python list

Tuple

A Tuple is a collection with round brackets() separated by commas which is ordered and unchangeable. Tuples are just like lists in terms of indexing, nested objects and repetition but you cannot change the elements of a tuple once it is assigned unlike lists, elements can be changed.


Python tuple

Dictionary

Dictionaries, in Python, are used to store values in {key:value} pairs. Keys in Dictionaries are unique and values may not be. Dictionaries are indexed by keys and each key can be "map" or "associate" to value objects. Each key in dictionary is separated from its value by a : (colon), the items are separated by commas, and the key and value is enclosed in {} (curly braces).

dict = {'ID': 1001, 'Name': 'John', 'Age': 12} print "dict['ID']: ", dict['ID'] print "dict['Name']: ", dict['Name']
output
dict['ID']: 1001 dict['Name']: John

Sets

Sets in Python are used to store unordered collection data type in a single variable and has no duplicate elements. Sets are typically used for mathematical operations like union, intersection, difference and complement etc.

my_set = set(('One','Two','Three','Four')) print(my_set)
output
{'Three', 'One', 'Four', 'Two'}
More on.... Python Data Structures