Lists/Sets/Dictionaries/Tuples in Python

Explore all the key concepts of Lists/Sets/Dictionaries/Tuples in Python related to Data Science

Lists/Sets/Dictionaries/Tuples in Python

Introduction to Lists in Python

In Python, a list is a dynamic and ordered collection of elements, enclosed in square brackets ([]).

  • Lists are mutable, allowing for easy modification, addition, and removal of elements.
  • They support various operations like indexing, slicing, and concatenation.
  • Lists can hold heterogeneous data types, making them versatile for storing different kinds of information.
  • Python’s built-in methods offer convenient ways to manipulate lists, making them a fundamental and flexible data structure in the language.

Definition:

  • A list is created by placing items inside square brackets [], separated by commas.
Python
my_list = [1, 2, 3, 'hello', 4.5]

To check datatype

Python
type(my_list)
list

Indexing:

  • Items in a list are ordered, and you can access them using zero-based indexing.
Python
first_item = my_list[0]  # Access the first item (1)
print(first_item)
1

Mutability:

  • Lists can be modified after creation. You can change, add, or remove elements.
Python
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]

Slicing:

  • You can extract a subset of a list using slicing.
Python
subset = my_list[1:4]    # Get items from index 1 to 3
print(subset)
['world', 'hello', 4.5]

Length:

  • The len() function returns the number of elements in a list.
Python
length = len(my_list)    # Returns 5
print(length)
5

Common Operations:

  • Lists support various operations like concatenation, repetition, and more.
Python
new_list = my_list + [7, 8]     # Concatenation
print(new_list)
[1, 'world', 'hello', 4.5, 6, 7, 8]
Python
repeated_list = my_list * 2     # Repetition
print(repeated_list)
[1, 'world', 'hello', 4.5, 6, 1, 'world', 'hello', 4.5, 6]

Nested Lists:

  • You can have lists inside lists, creating nested structures.
Python
nested_list = [1, [2, 3], 'hello']
print(nested_list)
[1, [2, 3], 'hello']
Python
print(nested_list[1])
[2, 3]

Common Methods:

  • Lists come with built-in methods for manipulation, such as append(), remove(), pop(), sort(), and more.
Python
my_list.append(9)       # Add an item to the end
print(my_list)
[1, 'world', 'hello', 4.5, 6, 9]
Python
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

Python
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.

Python
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.

Python
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.

Python
my_list = [10, 20, 30, 20, 40]
index_of_20 = my_list.index(20)
print(index_of_20) 
1

list.index(element, start, end)

  • element: The value to be searched in the list.
  • start (optional): The index from where the search begins. Default is 0.
  • end (optional): The index at which the search ends. Default is the end of the list.
Python
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

Sets in Python

In Python, a set is a versatile and unordered collection of unique elements.

  • It is defined by curly braces {} or created using the set() constructor.
  • Sets automatically enforce uniqueness, ensuring each element appears only once.
  • Ideal for scenarios requiring unique item storage or mathematical set operations, sets in Python provide simplicity and efficiency for tasks like membership checks, unions, intersections, and differences.

Uniqueness:

  • Sets do not allow duplicate elements. If you try to add an element that already exists in the set, it won’t be added again.
Python
my_set = {1, 2, 3, 3, 4}
print(my_set) 
{1, 2, 3, 4}

Note

No Indexing:

Unlike lists or tuples, sets are unordered, and elements cannot be accessed using indices.

Methods:

  • add(): Adds an element to the set.
  • remove(): Removes a specific element from the set.
  • discard(): Removes a specific element if it exists, without raising an error if it doesn’t.
  • pop(): Removes and returns an arbitrary element from the set.
  • clear(): Removes all elements from the set.
Python
my_set.add(5)
print(my_set)
{1, 2, 3, 4, 5}
Python
my_set.remove(2)
print(my_set)
{1, 3, 4, 5}
Python
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.

Python
my_set.pop()
print(my_set)
{3, 4, 5}
Python
my_set.clear()
print(my_set)
set()

All the elements are removed

Set Operations:

  • Union (| ): Combines elements from two sets, excluding duplicates.
  • Intersection (&): Retrieves common elements between two sets.
  • Difference (-): Returns elements present in the first set but not in the second.
  • Symmetric Difference (^): Returns elements present in either of the sets, but not in both.
Python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2   #set2.union(set1)
print(union_set)
{1, 2, 3, 4, 5}
Python
intersection_set = set1 & set2     #set2.intersection(set1)
print(intersection_set) 
{3}
Python
difference_set = set1 - set2       #set1.difference(set2)
print(difference_set)
{1, 2}
Python
 print(set1.difference(set2))
{1, 2}
Python
sym_diff_set = set1 ^ set2
print(sym_diff_set)
{1, 2, 4, 5}

Frozen Sets:

  • An immutable version of a set is called a frozen set. Once created, its elements cannot be modified.
Python
frozen_set = frozenset([1, 2, 3])

Tuples in Python

In Python, a tuple is a versatile and ordered data structure used to store a collection of elements.

  • Tuples are defined using parentheses () and contain comma-separated values.
  • One distinctive feature is their immutability, meaning once created, the elements cannot be modified. - - Tuples support common operations like indexing, slicing, and nesting, making them an efficient choice for organizing and accessing data in a structured manner.
Python
# Creating a tuple
my_tuple = (1, 2, 'hello')
print(my_tuple)
(1, 2, 'hello')
Python
# Accessing elements
first_element = my_tuple[0]
second_element = my_tuple[2]
print(first_element)
print(second_element)
1
hello
Python
# 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

Python
my_tuple[0] = 2

Dictionary in Python

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.

  • Each key in the dictionary is unique and serves as a reference to its associated value.
  • Dictionaries are created using curly braces {} and provide fast and efficient access to values based on their keys.
  • They are commonly used for tasks such as mapping, indexing, and storing configurations, making them a powerful tool for handling diverse data relationships in a concise and readable manner.
Python
my_dict = {}  # Creating an empty dictionary
type(my_dict)
dict
Python
#Adding Key-Value Pairs:

my_dict['key1'] = 'value1'
my_dict['key2'] = 42

print(my_dict)
{'key1': 'value1', 'key2': 42}
Python
# Retrieves the value associated with 'key1'
value = my_dict['key1']  
print(value)
value1

Dictionary Methods:

  • keys(): Returns a list of all keys.
  • values(): Returns a list of all values.
  • items(): Returns a list of key-value pairs (tuples).
Python
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)])
Python
#Checking if a Key Exists:

if 'key1' in my_dict:
    print("Key 'key1' exists!")
Key 'key1' exists!
Python
#Updating Values:
my_dict['key1'] = 'new_value'
print(my_dict)
{'key1': 'new_value', 'key2': 42}
Python
#Removing Key-Value Pairs:
del my_dict['key1']  # Removes the key 'key1' and its associated value
print(my_dict)
{'key2': 42}

Dictionary Comprehension:

Similar to list comprehensions, you can create dictionaries in a concise manner.

Python
squares = {x: x*x for x in range(1, 6)}
print(squares)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Iterating over Keys:

  • You can use a for loop to iterate over the keys, values, or key-value pairs of a dictionary.
Python
my_dict = {'a': 1, 'b': 2, 'c': 3}

for key in my_dict:
    print(key)
a
b
c

Iterating over Values:ΒΆ

Python
my_dict = {'a': 1, 'b': 2, 'c': 3}

for value in my_dict.values():
    print(value)
1
2
3

Iterating over Key-Value Pairs:

Python
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

Nested Dictionary

A nested dictionary in Python is a dictionary that contains other dictionaries as values.

Python
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