|
| 1 | +# use '#' instead of // like other coding lang for same purpose. |
| 2 | +cars1 = ["Ford", "Volvo", "BMW"] # array - creates a list of cars |
| 3 | + |
| 4 | +# check https://www.w3schools.com/python/python_arrays.asp for array func |
| 5 | + |
| 6 | +# note: python does not have 'arrays' by technicality, can use lists to take func - will refer as 'arrays' in my case |
| 7 | + |
| 8 | +x = cars1[0] # create an x variable and assign the first item in the cars array to it |
| 9 | + |
| 10 | +print(x) # prints x |
| 11 | + |
| 12 | +user3 = "human3" # creates a variable and assign it a value |
| 13 | +users = ["human1", "human2", user3] # new array |
| 14 | + |
| 15 | +for y in users: |
| 16 | + print(y) |
| 17 | + |
| 18 | +users.append("human4") # .append is an add method to an array |
| 19 | +print(users[3]) |
| 20 | + |
| 21 | +print("removed list") |
| 22 | +users.pop(2) # .pop is a remove method to an array, in this case, removes the third item in the array |
| 23 | + |
| 24 | +users.remove("human1") #.remove is also a remove method to an array, in this case, will remove the item with 'human1' - only the first occurance of 'human1' - i.e one will be removed, not all |
| 25 | + |
| 26 | +for y in users: |
| 27 | + print(y) # check list again, result human2 + human4 |
| 28 | + |
| 29 | + |
| 30 | +# cars func examples |
| 31 | + |
| 32 | +# car2 func |
| 33 | +# A function that returns the 'year' value: |
| 34 | +def funcCar2(e): |
| 35 | + return e['year'] |
| 36 | + |
| 37 | +cars2 = [ |
| 38 | + {'car': 'Ford', 'year': 2005}, |
| 39 | + {'car': 'Mitsubishi', 'year': 2000}, |
| 40 | + {'car': 'BMW', 'year': 2019}, |
| 41 | + {'car': 'VW', 'year': 2011} |
| 42 | +] |
| 43 | + |
| 44 | +cars2.sort(key=funcCar2) |
| 45 | + |
| 46 | +print(cars2) |
| 47 | + |
| 48 | +# car3 func |
| 49 | +# a functon that returns the length of a value |
| 50 | +def funcCar3(e): |
| 51 | + return len(e) |
| 52 | + |
| 53 | +cars3 = ['Ford', 'Mitsubishi', 'BMW', 'VW'] |
| 54 | + |
| 55 | +cars3.sort(reverse=True, key=funcCar3) |
| 56 | + |
| 57 | +print(cars3) |
| 58 | + |
| 59 | + |
| 60 | + |
0 commit comments