Lists
List is a collection which is ordered.
Lists are mutable (changeable) .
Allows duplicate members
Brackets used to represent: []
Lists are like arrays declared in other languages.
list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[0]
1
Tuples
Collection of items which is ordered.
Tuples are immutable (unchangeable) .
Brackets used to represent: ()
Only difference between tuples and lists are that lists can be changed.
Tuples are faster than lists as they are immutable.
location = (13.4125, 103.866667)
print("Latitude:", location[0])
print("Longitude:", location[1])
Sets
Collection of Unordered and Unindexed items.
Sets are mutable (changeable).
Does not take duplicate Values.
Sets are unordered, so you cannot be sure in which order the items will appear.
Brackets used to represent: { }.
Sets are not faster than lists however they have a upper hand when it comes to membership testing.
numbers = [1, 2, 6, 3, 1, 1, 6]
unique_nums = set(numbers)
print(unique_nums)
output:
{1, 2, 3, 6}
Dictionaries
Key:Value Pair in Python
A dictionary is a collection which is unordered, changeable and indexed.
In Python dictionaries are written with curly brackets, and they have keys and values.
Brackets used to represent: {}.
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print(elements["helium"]) # print the value mapped to "helium"
elements["lithium"] = 3 # insert "lithium" with a value of 3 into the dictionary
Compound Data Structures
We can include containers in other containers to create compound data structures. For example, this dictionary maps keys to values that are also dictionaries!
elements = {"hydrogen": {"number": 1,
"weight": 1.00794,
"symbol": "H"},
"helium": {"number": 2,
"weight": 4.002602,
"symbol": "He"}}
We can access elements in this nested dictionary like this.
helium = elements["helium"] # get the helium dictionary
hydrogen_weight = elements["hydrogen"]["weight"] # get hydrogen's weight
You can also add a new key to the element dictionary.
oxygen = {"number":8,"weight":15.999,"symbol":"O"} # create a new oxygen dictionary
elements["oxygen"] = oxygen # assign 'oxygen' as a key to the elements dictionary
print('elements = ', elements)
Output is:
elements = {"hydrogen": {"number": 1, "weight": 1.00794, "symbol": 'H'}, "helium": {"number": 2, "weight": 4.002602, "symbol": "He"}, "oxygen": {"number": 8, "weight": 15.999, "symbol": "O"}}
Top comments (2)