Python Data Structures
This page provides an introduction to python data structures.
Lists
Lists are ordered and changable, and allow duplicates.
fruits = ["apple", "banana", "orange", "coconut"]
# o/p: ['apple', 'banana', 'orange', 'coconut']
print(fruits[0::2])
# o/p: ['apple', 'orange']
# length
len(fruits)
# o/p: 4
# in
print("apple" in fruits)
# o/p: True
# reassign a value
fruits[0] = "pineapple"
# o/p: ['pineapple', 'banana', 'orange', 'coconut']
# append
fruits.append("apple")
# o/p: ['pineapple', 'banana', 'orange', 'coconut', 'apple']
# remove
fruits.remove("pineapple")
# o/p: ['banana', 'orange', 'coconut', 'apple']
# insert
fruits.insert(0, "pineapple")
# o/p: ['pineapple', 'banana', 'orange', 'coconut', 'apple']
# sort
fruits.sort()
# o/p: ['apple', 'banana', 'coconut', 'orange', 'pineapple']
# reverse - just reverses a list not in any order.
fruits.reverse()
# o/p: ['pineapple', 'orange', 'coconut', 'banana', 'apple']
# index
print(fruits.index("apple"))
# o/p: 4
# count
print(fruits.count("apple"))
# o/p: 1
# clear
fruits.clear()
# o/p: []
# lists all the methods availble for a collection
print(dir(fruits))
info
To list all the method available for a collection, call dir function.
Sets
Sets are unordered and doesn't allow duplicates.
fruits_set = {"apple", "banana", "orange", "coconut"}
# o/p: {'coconut', 'orange', 'apple', 'banana'}
# add
fruits_set.add("pineapple")
# o/p: {'pineapple', 'orange', 'coconut', 'apple', 'banana'}
# remove
fruits_set.remove("apple")
# o/p: {'pineapple', 'orange', 'coconut', 'banana'}
# pop
fruits_set.pop()
# o/p: 'pineapple'
# clean
fruits_set.clear()
# o/p: set()
Tuples
Tuples are ordered and unchangble, and allow duplicates.
fruits_tuple = ("apple", "orange", "banana", "coconut")
# len
len(fruits_tuple)
# o/p: 4
# in
"apple" in fruits_tuple
# o/p: True
# index
fruits_tuple.index("apple")
# o/p: 0
# count
fruits_tuple.count("coconut")
# o/p: 1
2D Lists
fruits_2d = ["apple", "banana", "orange"]
vegetables_2d = ["tomatos", "potatos"]
groceries = [fruits_2d, vegetables_2d]
# o/p: [['apple', 'banana', 'orange'], ['tomatos', 'potatos']]
# iterator over every elements
for collection in groceries:
for food in collection:
print(food, end =" ")
print()
# o/p:
# apple banana orange
# tomatos potatos
exotic_vegetables_2d = [("lotus root", "karela")]
groceries.append(exotic_vegetables_2d)
for collection in groceries:
for food in collection:
print(food, end = " ")
print()
# o/p:
# apple banana orange
# tomatos potatos
# ('lotus root', 'karela')
Dictionaries
Dictionary is collection of key, value pair. It is ordered, changable, and doesn't allow duplicates.
capitals = {
"India": "New Delhi",
"United States of America": "Washington D.C"
}
# o/p: {'India': 'New Delhi', 'United States of America': 'Washington D.C'}
# get
print(capitals.get("United States of America"))
# o/p: Washington D.C
print(capitals.get("Japan"))
# o/p: None
# update
capitals.update({"Germany": "Berlin"})
# o/p: {'India': 'New Delhi', 'United States of America': 'Washington D.C', 'Germany': 'Berlin'}
# pop
capitals.pop("Germany")
# o/p:
# 'Berlin'
# {'India': 'New Delhi', 'United States of America': 'Washington D.C'}
# popitem - removes latest key value pair
capitals.popitem()
# o/p:
# ('United States of America', 'Washington D.C')
# {'India': 'New Delhi'}
# keys
capitals.keys()
# o/p: dict_keys(['India'])
# iterate over keys
for key in capitals.keys(): print(key)
# o/p: India
# values
capitals.values()
# o/p: dict_values(['New Delhi'])
# items
capitals.items()
# o/p: dict_items([('India', 'New Delhi')])
# iterate over key, value
for key, value in capitals.items(): print(f"key: {key}, value: {value}")
# o/p: key: India, value: New Delhi
List Comprehensions
doubles = [x * 2 for x in range(1, 11)]
#o/p: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
numbers = [-1, 4141.13, 44, -2, 2414, -3]
positive_numbers = [num for num in numbers if num >= 0]
# o/p: [4141.13, 44, 2414]
negative_numbers = [num for num in numbers if num < 0]
# o/p: [-1, -2, -3]
Sorting
# sorting list
fruits_list = ["Banana", "Apple", "Orage", "Coconut"]
fruits_list.sort()
print(fruits_list)
# sorting tuple
fruits_tuple = ("Banana", "Apple", "Orage", "Coconut")
fruits_tuple = tuple(sorted(fruits_tuple, reverse = True))
print(fruits_tuple)
# sorting dictionary
fruits_dict = {"Banana": 105, "Apple": 72, "Orage": 73, "Coconut": 354}
# sorting by key
fruits_dict_by_key = dict(
sorted(
fruits_dict.items(), key=lambda item: item[0], reverse =True
)
)
# sorting by value
fruits_dict_by_value = dict(
sorted(
fruits_dict.items(), key=lambda item: item[1], reverse =True
)
)
print(fruits_dict_by_key)
# o/p: {'Orage': 73, 'Coconut': 354, 'Banana': 105, 'Apple': 72}
print(fruits_dict_by_value)
# o/p: {'Coconut': 354, 'Banana': 105, 'Orage': 73, 'Apple': 72}
# sorting objects
class Fruit:
def __init__(self, name, calories):
self.name = name
self.calories = calories
def __str__(self):
return f"{self.name}: {self.calories}"
def __repr__(self):
return self.__str__()
fruits = [
Fruit("banana", 105),
Fruit("apple", 72),
Fruit("orange", 73),
Fruit("coconut", 354)
]
# sorting by name
fruits_sorted_by_name = sorted(fruits, key=lambda fruit: fruit.name, reverse=True)
for fruit in fruits_sorted_by_name: print(str(fruit))
# o/p:
# orange: 73
# coconut: 354
# banana: 105
# apple: 72
# sorting by calories
fruits_sorted_by_calories = sorted(
fruits, key=lambda fruit: fruit.calories, reverse=True
)
for fruit in fruits_sorted_by_calories: print(str(fruit))
# o/p:
# coconut: 354
# banana: 105
# orange: 73
# apple: 72