0% found this document useful (0 votes)
4 views

Python Basics & Data Structure

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Basics & Data Structure

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Data Manipulation Functions on Lists

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

 list.insert(index, item): insert() inserts an item at a specific index in the list,


shifting existing elements to make room for the new item.

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 the output of print(fruits) :

fruits = ["apple", "banana", "cherry"]


fruits.append("orange")
fruits.insert(1, "mango")
fruits.remove("banana")
popped_item = fruits.pop(2)
fruits.sort()
fruits.reverse()

print(fruits)

Output:

['orange', 'mango', 'cherry', 'apple']

Here's what happened step by step:

1. "orange" is added to the end of the list.


2. "mango" is inserted at index 1, pushing "banana" to index 2.
3. "banana" is removed from the list.
4. The item at index 2, which is "cherry", is popped and assigned to popped_item.
5. The list is sorted in ascending order, resulting in ['apple', 'cherry', 'mango',
'orange'].
6. The order of items is reversed, resulting in ['orange', 'mango', 'cherry',
'apple'].

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.

categories_dict = {"fruit": "apple", "color": "red", "shape": "round"}


keys_list = list(categories_dict.keys()) # Returns ["fruit", "color",
"shape"]

Output:

css
 keys_list = ["fruit", "color", "shape"]

 dictionary.values(): The values() method returns a list of all values in the


dictionary.

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.

categories_dict = {"fruit": "apple", "color": "red", "shape": "round"}

items_list = list(categories_dict.items()) # Returns [("fruit", "apple"),


("color", "red"), ("shape", "round")]

Output:

items_list = [("fruit", "apple"), ("color", "red"), ("shape", "round")]

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

categories_dict = {"fruit": "apple", "color": "red", "shape": "round"}

fruit = categories_dict.get("fruit") # Returns "apple"

size = categories_dict.get("size", "unknown") # Returns "unknown" as the


default
Output:

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.

categories_dict = {"fruit": "apple", "color": "red", "shape": "round"}

removed_color = categories_dict.pop("color") # Removes "color" and returns


"red"
unknown_size = categories_dict.pop("size", "unknown") # Returns "unknown"
as the default

Output:

makefile
removed_color = "red"
unknown_size = "unknown"

You might also like