Explore all the key concepts of Lists/Sets/Dictionaries/Tuples in Python related to Data Science
In Python, a list is a dynamic and ordered collection of elements, enclosed in square brackets ([]
).
my_list = [1, 2, 3, 'hello', 4.5]
type(my_list)
list
first_item = my_list[0] # Access the first item (1)
print(first_item)
1
my_list[2] = 'world' # Modify the third item
my_list.append(6) # Add an item to the end
del my_list[1] # Remove the second item
print(my_list)
[1, 'world', 'hello', 4.5, 6]
subset = my_list[1:4] # Get items from index 1 to 3
print(subset)
['world', 'hello', 4.5]
length = len(my_list) # Returns 5
print(length)
5
new_list = my_list + [7, 8] # Concatenation
print(new_list)
[1, 'world', 'hello', 4.5, 6, 7, 8]
repeated_list = my_list * 2 # Repetition
print(repeated_list)
[1, 'world', 'hello', 4.5, 6, 1, 'world', 'hello', 4.5, 6]
nested_list = [1, [2, 3], 'hello']
print(nested_list)
[1, [2, 3], 'hello']
print(nested_list[1])
[2, 3]
my_list.append(9) # Add an item to the end
print(my_list)
[1, 'world', 'hello', 4.5, 6, 9]
my_list.remove('hello') # Remove the specified item
print(my_list)
[1, 'world', 4.5, 6, 9]
*Note: -Here for sorting the data/items in the list should has to be of same data type
sorted_list = [1,4,9,7,3,9]
sorted_list.sort() # Sort the list in ascending order
sorted_list
[1, 3, 4, 7, 9, 9]
The count() method is used to count the number of occurrences of a specified element in a list.
sorted_list.count(9)
2
The pop() method is used to remove and return an element from a specific index in the list.
If no index is provided, it removes and returns the last element by default.
my_list = [1, 2, 3, 4, 5]
popped_element = my_list.pop(2) # Removes and returns element at index 2 (3)
print(my_list)
print(popped_element)
[1, 2, 4, 5]
3
The index() method is used to find the index of the first occurrence of a specified element in the list.
It takes one argument, the element whose index you want to find.
my_list = [10, 20, 30, 20, 40]
index_of_20 = my_list.index(20)
print(index_of_20)
1
list.index(element, start, end)
my_list = [10, 20, 30, 20, 40]
index_of_20 = my_list.index(20) # Searches for the first occurrence of 20
print(index_of_20)
index_of_20_after_index_1 = my_list.index(20, 2, 4) # Searches for 20 starting between index 2 and 4
print(index_of_20_after_index_1)
1
3
In Python, a set is a versatile and unordered collection of unique elements.
my_set = {1, 2, 3, 3, 4}
print(my_set)
{1, 2, 3, 4}
Note
Unlike lists or tuples, sets are unordered, and elements cannot be accessed using indices.
my_set.add(5)
print(my_set)
{1, 2, 3, 4, 5}
my_set.remove(2)
print(my_set)
{1, 3, 4, 5}
my_set.discard(9)
print(my_set)
{1, 3, 4, 5}
Here you can see in the above example there is no error shown even though there is no element specifically ‘9’ in the set.
my_set.pop()
print(my_set)
{3, 4, 5}
my_set.clear()
print(my_set)
set()
All the elements are removed
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 #set2.union(set1)
print(union_set)
{1, 2, 3, 4, 5}
intersection_set = set1 & set2 #set2.intersection(set1)
print(intersection_set)
{3}
difference_set = set1 - set2 #set1.difference(set2)
print(difference_set)
{1, 2}
print(set1.difference(set2))
{1, 2}
sym_diff_set = set1 ^ set2
print(sym_diff_set)
{1, 2, 4, 5}
frozen_set = frozenset([1, 2, 3])
In Python, a tuple is a versatile and ordered data structure used to store a collection of elements.
# Creating a tuple
my_tuple = (1, 2, 'hello')
print(my_tuple)
(1, 2, 'hello')
# Accessing elements
first_element = my_tuple[0]
second_element = my_tuple[2]
print(first_element)
print(second_element)
1
hello
# Slicing
subset_tuple = my_tuple[1:3]
print(subset_tuple)
(2, 'hello')
*Note: Item assinging in tuple is not possible running below code will show error
my_tuple[0] = 2
In Python, a dictionary is a versatile and fundamental data structure that allows you to store and organize data using a collection of key-value pairs.
my_dict = {} # Creating an empty dictionary
type(my_dict)
dict
#Adding Key-Value Pairs:
my_dict['key1'] = 'value1'
my_dict['key2'] = 42
print(my_dict)
{'key1': 'value1', 'key2': 42}
# Retrieves the value associated with 'key1'
value = my_dict['key1']
print(value)
value1
keys_list = my_dict.keys()
values_list = my_dict.values()
items_list = my_dict.items()
print(keys_list)
print(values_list)
print(items_list)
dict_keys(['key1', 'key2'])
dict_values(['value1', 42])
dict_items([('key1', 'value1'), ('key2', 42)])
#Checking if a Key Exists:
if 'key1' in my_dict:
print("Key 'key1' exists!")
Key 'key1' exists!
#Updating Values:
my_dict['key1'] = 'new_value'
print(my_dict)
{'key1': 'new_value', 'key2': 42}
#Removing Key-Value Pairs:
del my_dict['key1'] # Removes the key 'key1' and its associated value
print(my_dict)
{'key2': 42}
Similar to list comprehensions, you can create dictionaries in a concise manner.
squares = {x: x*x for x in range(1, 6)}
print(squares)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(key)
a
b
c
my_dict = {'a': 1, 'b': 2, 'c': 3}
for value in my_dict.values():
print(value)
1
2
3
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
A nested dictionary in Python is a dictionary that contains other dictionaries as values.
nested_dict = {
'outer_key1': {
'inner_key1': 'value1',
'inner_key2': 'value2'
},
'outer_key2': {
'inner_key3': 'value3',
'inner_key4': 'value4'
}
}
print(nested_dict['outer_key1']['inner_key1'])
value1