Tasks studies - laboratory
Project maintained by dawidolko Hosted on GitHub Pages — Theme by dawidolko
Python Scripting Language - Lab 3
Scripting Language Lab3
Arrays
Arrays in Python are not like arrays in Java or C but are more similar to lists.
An array is a data structure that stores values of the same type.
This is the main difference between arrays and lists in Python.
To use arrays in Python, you need to import the array module from Python’s standard libraries because arrays are not considered primitive data types like integers or strings.
from array import *
Below is an example of an array declaration:
```Python
array_name = array(data_type_code, [initial_values])
| Data Type Code | Description |
|---|---|
b |
Represents a signed integer of size 1 byte |
B |
Represents an unsigned integer of size 1 byte |
c |
Represents a character of size 1 byte |
u |
Represents a Unicode character of size 2 bytes |
h |
Represents a signed integer of size 2 bytes |
H |
Represents an unsigned integer of size 2 bytes |
i |
Represents a signed integer of size 2 bytes |
I |
Represents an unsigned integer of size 2 bytes |
w |
Represents a Unicode character of size 4 bytes |
l |
Represents a signed integer of size 4 bytes |
L |
Represents an unsigned integer of size 4 bytes |
f |
Represents a floating-point number of size 4 bytes |
d |
Represents a floating-point number of size 8 bytes |
Individual elements can be accessed using their index, and arrays are indexed starting from 0.
from builtins import print
my_array = array('i', [1, 2, 3, 4, 5])
print(my_array[1])
print(my_array[2])
print(my_array[0])
print()
my_array = array('i', [1, 2, 3, 4, 5])
for i in my_array:
print(i)
Adding Elements to an Array
Adding an element to an array using the append method:
my_array = array('i', [1, 2, 3, 4, 5])
my_array.append(6)
Adding an element to a specific index using the insert method:
my_array.insert(0, 0)
The inserted value is placed in the appropriate position in the array, shifting the remaining elements by one index.
Extending an Array
In Python, you can extend an array with more than one value using the extend method:
my_array = array('i', [1, 2, 3, 4, 5])
my_extend_array = array("i", [6, 7, 8, 9, 10])
my_array.extend(my_extend_array)
print(my_array)
You can also add elements from a list to an array using the fromlist method:
my_array = array('i', [1, 2, 3, 4, 5])
c = [11, 12, 13]
my_array.fromlist(c)
Removing Elements from an Array
Removing an element from an array using the remove method:
my_array = array('i', [1, 2, 3, 4, 5])
my_array.remove(4)
Removing the last element from an array using the pop method:
my_array = array('i', [1, 2, 3, 4, 5])
my_array.pop()
Finding Elements in an Array
Using the index method to find the first occurrence of a value:
my_array = array('i', [1, 2, 3, 4, 5])
print(my_array.index(5))
my_array = array('i', [1, 2, 3, 3, 5])
print(my_array.index(3))
Reversing an Array
Using the reverse method:
my_array = array('i', [1, 2, 3, 4, 5])
my_array.reverse()
print(my_array)
Getting Array Information
Finding the memory address and length of an array:
my_array = array('i', [1, 2, 3, 4, 5])
print(my_array.buffer_info())
Counting the occurrences of a specific value:
my_array = array('i', [1, 2, 3, 3, 5])
print(my_array.count(3))
Converting an Array
Converting an array to a string:
my_array1 = array('u', ['s', 'p', 'a', 'm'])
print(my_array1)
print(my_array1.tounicode())
Converting an array to a list:
my_array = array('i', [1, 2, 3, 4])
list_version = my_array.tolist()
Dictionaries
Dictionaries are data structures used to map arbitrary keys to values.
They can be indexed similarly to lists using square brackets containing the key.
ages = {"I": 78, "You": 20, "Him": 24}
print(ages["I"])
print(ages["Him"])
Each dictionary element is represented as a key: value pair.
If a non-existent key is accessed, it raises a KeyError.
colors = {
"red": [255, 0, 0],
"green": [0, 255, 0],
"blue": [0, 0, 255]
}
print(colors["red"])
print(colors["yellow"]) # KeyError
Only immutable objects can be used as dictionary keys. Lists and arrays cannot be used as keys.
bad_dict = {[1, 2, 3]: "one two three"} # TypeError
Dictionary Methods
Checking if a key exists in a dictionary using in and not in:
nums = {1: "one", 2: "two", 3: "three"}
print(1 in nums)
print("three" in nums)
print(4 not in nums)
Getting values using the get method:
pairs = {
"orange": [2, 3, 40], 0: "spam", True: False, None: "True", 2: "apple"
}
print(pairs.get("orange"))
print(pairs.get(7))
print(pairs.get(1235, "not in dictionary"))
print(len(pairs))
Merging dictionaries:
fish = {'name': "Nemo", 'hands': "fins", 'special': "gills"}
dog = {'name': "Clifford", 'hands': "paws", 'color': "red"}
# Python 3.5+
fishdog = {**fish, **dog}
print(fishdog)
Slicing Lists
Extracting specific portions of a list:
squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(squares[2:6])
print(squares[:7])
print(squares[::2])
Useful String Methods
join- joins a list of strings using a separatorreplace- replaces a substring with anotherstartswith/endswith- checks if a string starts/ends with a substringlower/upper- converts string to lowercase/uppercasesplit- splits a string into a listformat- formats a string with arguments
print(",".join(["spam", "eggs", "spam"]))
print("Hello Me".replace("Me", "world"))
print("This is a sentence.".upper())
print("Numbers: {0} {1} {2}".format(4, 5, 6))
Tasks to Complete
2-6 must be added to GitHub.
