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

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.
my_list = [1, 2, 3, 'hello', 4.5]
To check datatype
type(my_list)list
Indexing:
- Items in a list are ordered, and you can access them using zero-based indexing.
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.
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.
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.
length = len(my_list) # Returns 5
print(length)5
Common Operations:
- Lists support various operations like concatenation, repetition, and more.
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 Lists:
- You can have lists inside lists, creating nested structures.
nested_list = [1, [2, 3], 'hello']
print(nested_list)[1, [2, 3], 'hello']
print(nested_list[1])[2, 3]
Common Methods:
- Lists come with built-in methods for manipulation, such as append(), remove(), pop(), sort(), and more.
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)
- 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.
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.
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.
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
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.
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 Sets:
- An immutable version of a set is called a frozen set. Once created, its elements cannot be modified.
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.
# 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] = 2Dictionary 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.
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
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).
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}
Dictionary Comprehension:
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}
Iterating over Keys:
- You can use a for loop to iterate over the keys, values, or key-value pairs of a dictionary.
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(key)
a
b
c
Iterating over Values:¶
my_dict = {'a': 1, 'b': 2, 'c': 3}
for value in my_dict.values():
print(value)
1
2
3
Iterating over Key-Value Pairs:
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.
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
On this page
- Definition:
- To check datatype
- Indexing:
- Mutability:
- Slicing:
- Length:
- Common Operations:
- Nested Lists:
- Common Methods:
- Uniqueness:
- No Indexing:
- Methods:
- Set Operations:
- Frozen Sets:
- Dictionary Methods:
- Dictionary Comprehension:
- Iterating over Keys:
- Iterating over Values:¶
- Iterating over Key-Value Pairs:
- Nested Dictionary
Keep exploring
matched by tag + title overlap
Read next
A Beginners Guide to Pandas in Python
Learn the essentials of Python's pandas library in this beginner's guide. Discover how to effortlessly manipulate and analyze data for your projects.
#python#data-analyst#data-scienceA Beginners Guide to Numpy in Python
Discover NumPy basics in Python! Learn to manipulate data effortlessly with arrays and boost your coding skills. Perfect for beginners diving into numerical computing.
#python#data-analyst#data-scienceData Science in Microsoft Fabric
Learn how Microsoft Fabric simplifies data science from start to finish. Explore key steps, machine learning models, and efficient experimentation and model management with MLflow. Uncover the tools and techniques for data-driven…
#data-scienceBayes Theorem in Data Science
Imagine your job search during a recession 🧩. How likely are you to find a job given the economic downturn? 📉 That's where Bayes Theorem comes in!
#data-science