Python Basics & Data Structure
Python Basics & Data Structure
Lists:
len(list): This function returns the number of elements in a list. It's useful for determining
the length or size of a list.
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("length:", length)# Returns 5
list.append(item): The append() method adds an item to the end of a list, effectively
extending the list by one element.
my_list = [1, 2, 3]
my_list.append(4)
print ("new my_list:",my_list) # Adds 4 to the end of the list
my_list = [1, 2, 3]
my_list.insert(1, 4) # Inserts 4 at index 1, my_list becomes [1, 4, 2, 3]
list.remove(item): remove() removes the first occurrence of a specified item from the
list.
my_list = [1, 2, 3, 2, 4]
my_list.remove(2) # Removes the first occurrence of 2, my_list becomes [1,
3, 2, 4]
list.pop(index): The pop() method removes and returns the item at a specific index in
the list. If no index is provided, it removes and returns the last item.
my_list = [1, 2, 3, 4]
popped_item = my_list.pop(1) # Removes and returns the item at index 1 (2)
list.sort(): The sort() method arranges the elements of a list in ascending order. It
modifies the original list and does not return a new sorted list.
my_list = [4, 1, 3, 2]
my_list.sort() # Sorts the list in-place, my_list becomes [1, 2, 3, 4]
list.reverse(): reverse() reverses the order of items in the list. Similar to sort(), it
modifies the original list in-place.
1. my_list = [1, 2, 3, 4]
2. my_list.reverse() # Reverses the list in-place, my_list becomes [4,
3, 2, 1]
These basic functions are fundamental when working with lists in Python. They allow you to
manipulate the contents of a list, retrieve information about its size, and change its order.
print(fruits)
Output:
So, when you print fruits at the end of these operations, you get ['orange', 'mango',
'cherry', 'apple'].
Tuples:
Tuples are similar to lists in Python, but they have a key difference: they are immutable. This
means that once a tuple is created, its contents cannot be modified. However, you can
perform basic operations on tuples, such as accessing elements and creating new tuples.
Here's an explanation of some basic functions commonly used with tuples:
1. len(tuple): The len() function returns the number of elements in a tuple. It works
the same way as it does for lists.
python
my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple) # Returns 5
tuple.index(item): The index() method is used to find the index of the first
occurrence of a specific item in the tuple. It raises a ValueError if the item is not found.
python
my_tuple = (10, 20, 30, 20, 40)
index = my_tuple.index(20) # Returns 1 (index of the first occurrence of
20)
tuple.count(item): The count() method returns the number of times a specific item
appears in the tuple.
python
3. my_tuple = (10, 20, 30, 20, 40)
4. count = my_tuple.count(20) # Returns 2 (20 appears twice in the
tuple)
These basic functions are useful for working with tuples in Python, even though you cannot
modify the contents of a tuple after it's created. Tuples are often used when you need a
collection of items that should remain constant throughout the program's execution, such as
coordinates or configuration settings.
Sets in Python are unordered collections of unique elements. They are useful when you
need to store a collection of values where each value is distinct.
len(set): The len() function returns the number of elements in a set. Since sets contain
only unique elements, this function provides the count of distinct elements.
python
categories = {"apple", "banana", "cherry", "banana"}
num_categories = len(categories) # Returns 3 (only unique elements are
counted)
Output:
makefile
num_categories = 3
set.add(item): The add() method adds an item to the set if it doesn't already exist. If
the item is already in the set, it won't add a duplicate.
python
categories = {"apple", "banana", "cherry"}
categories.add("date") # Adds "date" to the set
categories.add("banana") # No effect, as "banana" is already in the set
Output:
makefile
categories = {"apple", "banana", "cherry", "date"}
set.remove(item): The remove() method removes a specified item from the set if it
exists. It raises a KeyError if the item is not found in the set.
python
categories = {"apple", "banana", "cherry"}
categories.remove("banana") # Removes "banana" from the set
Output:
makefile
categories = {"apple", "cherry"}
set.discard(item): The discard() method also removes an item from the set if it
exists. However, it does not raise an error if the item is not found.
python
categories = {"apple", "banana", "cherry"}
categories.discard("date") # No error, as "date" is not in the set
Output:
makefile
categories = {"apple", "banana", "cherry"}
set.clear(): The clear() method removes all items from the set, leaving it empty.
python
categories = {"apple", "banana", "cherry"}
categories.clear() # Empties the set
Output:
scss
1. categories = set()
These examples illustrate how these basic set functions work with categorical values, and the
corresponding outputs show the changes to the set after each operation.
Dictionaries in Python are collections of key-value pairs that allow for efficient storage
and retrieval of data.
len(dictionary): The len() function returns the number of key-value pairs in the
dictionary.
python
categories_dict = {"fruit": "apple", "color": "red", "shape": "round"}
result = len(categories_dict) # Returns 3
print (result)
Output:
makefile
num_categories = 3
dictionary.keys(): The keys() method returns a list of all keys in the dictionary.
Output:
css
keys_list = ["fruit", "color", "shape"]
python
categories_dict = {"fruit": "apple", "color": "red", "shape": "round"}
values_list = list(categories_dict.values()) # Returns ["apple", "red",
"round"]
Output:
css
values_list = ["apple", "red", "round"]
dictionary.items(): The items() method returns a list of all key-value pairs in the
dictionary as tuples.
Output:
dictionary.get(key): The get() method returns the value associated with the specified
key. If the key is not found, it returns None by default or a specified default value.
makefile
fruit = "apple"
size = "unknown"
dictionary.pop(key): The pop() method removes the key-value pair with the specified
key and returns the value. If the key is not found, it raises a KeyError or returns a specified
default value.
Output:
makefile
removed_color = "red"
unknown_size = "unknown"