2017 started my learning journey with Python.
07 Sep 2022
This note here will include only reminders and new learnings for basic Python objects knowledge & syntax.
Python resources within this site:
Snippets: Python Snippets
Main libraries: [Nic Notes: Libraries tag]
Simple scripts: [Nic Notes: Scripts tag]
Projects: [Nic Notes: Projects category]See also note from 2 years ago - still relevant (albeit using different tools now):
My guide to start learning programming in Python (for Business People)
Python objects & syntax
Lists
- Ordered: the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list.
- Changeable: we can change, add, and remove items in a list after it has been created.
- Allow Duplicates: can have items with the same value.
snippets
(list name for examples below: highlights
)
Add at index: highlights.insert(position, element)
Fetch last element of list: highlights[-1:][0]
Tuples
- Indexed: the first item has index [0], the second item has index [1] etc.
- Ordered: the items have a defined order, and that order will not change.
- Unchangeable: cannot change, add or remove items after the tuple has been created.
- Allow Duplicates: can have items with the same value.
11 Sep 2022
Sets
Sets are lists of unique values. Its primary feature is that you can add as much to it as you want, and if a value is already in it, it will simply be skipped.
So to get all the unique values from a list, you can just make it a set, eg unique_values = set(my_list)
or in a for loop: for x in y: unique_values.add(x)
.
For example:
list_emails = []
set_emails = set()
for root, dirs, files in os.walk("log"):
for name in files:
if name.endswith((".txt")):
file_path = f"{root}/{name}"
with open(file_path, 'r') as df:
lines = df.readlines()
for line in lines:
set_emails.add(line) # this will create a set of unique values
list_emails.append(line) # this will keep all items, ie include duplicates
print(f"\nlen set_emails: {len(set_emails)}")
print(f"\nlen list_emails: {len(list_emails)}")
prints:
len set_emails: 763
len list_emails: 72090