Day 1: Data Types
What I learnt
- Numbers
- Strings
- Booleans
- Lists
- Tuples
- Sets
- Dictionaries
Numbers
Numbers are used to represent integers, floating point numbers, and complex numbers.
- Integers
>>> 1
1
>>> 2
2
- Floats: Floating point numbers are represented in Python using decimal points. Also known as real numbers.
>>> 1.1
1.1
- Complex Numbers: Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.
>>> 1 + 2j
(1+2j)
Strings
Strings are used to represent text data, the text is given under quote marks. Python treats single quotes the same as double quotes.
- Single Quotes
- Double Quotes
- Triple Quotes: Triple quotes are used to span the string across multiple lines.
>>> 'Hello World'
'Hello World'
>>> "Hello World"
'Hello World'
>>> """Hello World"""
'Hello World'
- String Concatenation: Strings can be concatenated (glued together) with the + operator, and repeated with *:
>>> 'Hello' + 'World'
'HelloWorld'
>>> 'Hello' * 3
'HelloHelloHello'
- String Slicing: Strings can be sliced (subscripted), with the syntax [start:stop:step]. If start is omitted, it is default to 0. If stop is omitted, it is default to the end of the string. If step is omitted, it is default to 1.
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
>>> word[:2] + word[2:]
'Python'
- String Methods: Strings have a bunch of useful methods. Some of them are listed below.
>>> word = 'Python'
>>> word.upper()
'PYTHON'
>>> word.lower()
'python'
>>> word.startswith('P')
True
>>> word.endswith('n')
True
You can find more string methods here.
Booleans
Booleans represent one of two values: True or False.
>>> True
True
>>> False
False
Lists
A list is a collection of items in a particular order.
You can make a list that includes the letters of the alphabet, the digits from 0-9.
You can put anything you want into a list, and the items in your list don't have to be related in any particular way.
The syntax for defining a list is to enclose the items in square brackets, with commas between them.
>>> [1, 2, 3]
[1, 2, 3]
>>> ['Hello', 'World']
['Hello', 'World']
>>> [1, 'Hello', 2.5]
[1, 'Hello', 2.5]
Characteristics of Lists:
- Ordered
- Mutable
- Allows Duplicate Elements
Example of List and Manipulating it
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0])
- Slicing a list => When slicing a list, just as strings, it has 3 parts i.e [start:stop:stepover]
print(bicycles[1:3])
- Duplicating a list - [:] is used to create an entirely new copy of the existing list
new_bicycles = bicycles[1::2]
new_bicycles[0] = 'seat'
print(new_bicycles)
print(bicycles)
```
{% endraw %}
- Matrix: A matrix is a two-dimensional data structure that can store numbers or other types of data ie it's a liat that stores another list inside of them.
### Example of Matrix
{% raw %}
```python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[2][0])
```
### List Methods
- append() => This method adds an item to the end of the list
```python
bicycles.append('word')
- insert() => This method adds an item at a specific index
bicycles.insert(0, 'shoo')
- extend() => This method adds multiple items to the end of the list
bicycles.extend(['word2', 'word3'])
- remove() => This method removes an item from the list by its value and not by its index
bicycles.remove('word2')
- pop() => This method removes the last item from the list and returns the popped item
new_bask = bicycles.pop(0)
- clear() => This method removes all the items from the list and returns an empty list
bicycles.clear()
index() => This method returns the index of the first item with the specified value and returns an error if the value is not found
You can learn more about the index method here
print(bicycles.index('word3'))
- count() => This method returns the number of times the specified value appears in the list
print(bicycles.count('word3'))
Common List Patterns
bicycles.sort()
bicycles.reverse()
print(bicycles[::-1]) # This is used to reverse a list and it creates a new copy of the list
print(bicycles)
List Unpacking: This is used to assign multiple variables at once
a, b, c, *rest, d = bicycles
print(rest)
print(d)
Looping through a list
- For Loop
for bicycle in bicycles:
print(bicycle)
- Remove duplicates from a list
names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mosh', 'John', 'Anne', 'Jane', 'Bob', 'Anne']
duplicate_names = []
unique_names = []
for name in names:
if name not in unique_names:
unique_names.append(name)
else:
duplicate_names.append(name)
print(unique_names)
print(duplicate_names)
pictures = [
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0]
]
for row in pictures:
for pixels in row:
if pixels == 1:
print('\*', end='')
else:
print(' ', end='')
print('') # This is used to print a new line after each row
- While Loop
i = 0
while i < len(bicycles):
print(bicycles[i])
i += 1
- Looping through a list of dictionaries
users = [{'username': 'Jobizil', 'email': 'jobizil@email.com','age': 26},
{'username': 'Quill', 'email': 'quill@email.com', 'age': 22}]
for user in users:
print(user['username'])
List Comprehension: This is used to create a new list from an existing list
new_list = [expression for item in list if conditional]
new_list = [item['email'] for item in users]
print(new_list)
List Comprehension with if statement
new_list = [item['email'] for item in users if item['age'] > 25]
print(new_list)
Tuples: Just like Lists, Tuples are used to store multiple items in a single variable but they are stored within brackets (elements).
>>> (1, 2, 3)
(1, 2, 3)
>>> ('Hello', 'World')
('Hello', 'World')
>>> (1, 'Hello', 2.5)
(1, 'Hello', 2.5)
Characteristics of Tuple:
- Ordered
- Immutable
- Allows Duplicate Elements
Tuple Methods: You can learn more about the tuple methods here
Sets
A set is a collection which is unordered and unindexed. In Python, sets are written with curly brackets.
>>> {1, 2, 3}
{1, 2, 3}
>>> {'Hello', 'World'}
{'Hello', 'World'}
>>> {1, 'Hello', 2.5}
{1, 'Hello', 2.5}
Characteristics of Sets:
- Unordered
- Mutable
- Does Not Allow Duplicate Elements
Example of a set
fruits = {'apple', 'orange', 'apple', 'grape', 'pear', 'banana'}
fruits_2 = {'babana', 'pawpaw', 'apple', 'orange', 'pear', 'banana', 'mango'}
print(fruits)
Common Set Patterns
- Convert a list to a set
fruits_list = ['apple', 'orange', 'apple', 'grape', 'pear', 'banana']
fruits_set = set(fruits_list)
print(list(fruits_set))
- Remove duplicates from a list
fruits_list = ['apple', 'orange', 'apple', 'grape', 'pear', 'banana']
fruits_set = set(fruits_list)
print(list(fruits_set))
- Find the intersection of two lists
fruits_list = ['apple', 'orange', 'apple', 'grape', 'pear', 'banana']
fruits_list_2 = ['apple', 'orange', 'apple', 'grape', 'pear', 'banana', 'mango']
fruits_set = set(fruits_list)
fruits_set_2 = set(fruits_list_2)
print(fruits_set.intersection(fruits_set_2))
- Find the difference between two lists
print(fruits_set.difference(fruits_set_2))
print(fruits_set_2.difference(fruits_set))
- Find the union of two lists
print(fruits_set.union(fruits_set_2))
Set Methods
- add() => This method adds an element to the set
fruits.add('mango')
print(fruits)
- clear() => This method removes all the elements from the set
fruits.clear()
print(fruits)
- copy() => This method returns a copy of the set
fruits_copy = fruits.copy()
print(fruits_copy)
- difference() => This method returns a set containing the difference between two or more sets
print(fruits.difference(fruits_2))
print(fruits_2.difference(fruits))
- difference_update() => This method removes the items in this set that are also included in another, specified set and returns a set
print(fruits.difference_update(fruits_2))
print(fruits)
- discard() => This method removes the specified element from the set
fruits.discard('apple')
print(fruits)
- intersection() => This method returns a set that contains the similarity between two or more sets
print(fruits.intersection(fruits_2))
- intersection_update() => This method removes the items in this set that are not present in other, specified set(s) and returns a set
print(fruits.intersection_update(fruits_2))
- isdisjoint() => This method returns True if two sets have a null intersection
print(fruits.isdisjoint(fruits_2))
- issubset() => This method returns True if another set contains this set
print(fruits.issubset(fruits_2))
print(fruits_2.issubset(fruits))
- issuperset() => This method returns True if this set contains another set
print(fruits.issuperset(fruits_2))
print(fruits_2.issuperset(fruits))
- union() => This method returns a set that contains all items from the original set, and all items from the specified sets
print(fruits.union(fruits_2))
You can learn more about the set methods here
Dictionaries
A dictionary in Python is a collection of key-value pairs usually unordered. Each key is connected to a value, and you can use a key to access the value associated with that key. A key's value can be a number, a string, a list, or even another dictionary. In fact, you can use any object that you can create in Python as a value in a dictionary.
They store data values in key:value pairs within curly braces {elements}.
>>> {'name': 'John', 'age': 30}
{'name': 'John', 'age': 30}
>>> {'name': 'John', 'age': 30, 'name': 'Jane'}
{'name': 'Jane', 'age': 30}
Characteristics of Dictionaries:
- Unordered
- Mutable
- Does Not Allow Duplicate Keys
Example of a dictionary
user = {'username': 'Jobizil',
'email': 'jobizil@email.com',
'age': 25,
'color': 'blue',
'is_active': True,
'is_admin': True,
'is_staff': False,
}
print(user['username'])
Dictionary Methods
- get() => This method returns the value of the specified key
print(user.get('username'))
- keys() => This method returns a list of all the keys in the dictionary
print(user.keys())
print(user.values())
- items() => This method returns a list of tuples containing the key-value pairs
print(user.items())
- clear() => This method removes all the items from the dictionary and returns an empty dictionary
print(user.clear())
- pop() => This method removes the item with the specified key name and returns the value of the removed item
print(user.pop('username'))
- popitem() => This method removes the last inserted item and returns a tuple containing the key-value pair of the removed item
print(user.popitem())
- copy() => This method returns a copy of the dictionary
user_2 = user.copy()
print(user_2)
- update() => This method updates the dictionary with the specified key-value pairs
user.update({'username': 'Quill', 'email': 'quill@email.com'})
user_3 = user.copy()
print(user_3)
Read more about dictionary methods here
Common Dictionary Patterns
-
Looping through a dictionary
```python
for key, value in user.items():
print(f'Key: {key}')
print(f'Value: {value}')
-
Looping through a dictionary keys
for key in user.keys(): print(key) ``` {% endraw %}
-
Looping through a dictionary values
{% raw %}for value in user.values(): print(value)
Dictionary Comprehension:
Dictionary comprehension is a way to create a dictionary in a single line of code. It is a combination of a for loop and a dictionary.
Example of Dictionary Comprehension
```python
squared = {num: num**2 for num in [1, 2, 3, 4, 5]}
print(squared)
```
- Dictionary Comprehension with conditional logic
Dictionary comprehension with conditional logic is a way to create a dictionary in a single line of code. It is a combination of a for loop, a conditional statement and a dictionary.
Example of Dictionary Comprehension with conditional logic
```python
squared = {num: num**2 for num in [1, 2, 3, 4, 5] if num % 2 == 0}
print(squared)
```
Conclusion
I might not have covered everything in this article but I hope it helps you understand the basics of Python data structures. You can learn more about Python data structures here.
Also, I might not be able to update this article series as soon as I learn new things within my learning journey. But I will ensure I update it on my GitHub repo. You can check it out here.
Top comments (0)