Create array in Python (list) and Django

Posted under » Python » Django on 24 May 2022

Python Collections (Arrays). There are four collection data types in the Python programming language:

List is a collection which is ordered and changeable. Allows duplicate members.
eg. alist = ["durian", "rambutan", "manga"]
Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Some people prefer set because they are faster.
eg. atuple = ("waihong", "adam", "kelvin")
Set is a collection which is unordered and unindexed. No duplicate members. Set items are unchangeable, but you can remove items and add new items.
rg. aset = {"abibakrin", "umar", "uthman"}
Dictionary is a collection which is ordered and changeable. No duplicate members.
eg. thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
.

You can use dict to count duplicates.

To create a dictionary, the brackets turn curly. In PHP it is called an associative array and uses arrow (in PHP) instead colon in Python.

If you need more info of what you can do the collections,

print(dir(alist))
af = {'ahmad' : 'WENDY', 'sollihin' : 'CHOOI LENG'}

Please note the dictionary key (the first part 'ahmad') must be string. Looping for dictionary

for x in af :
    print(x, "->", af[x])

To begin, we initialise the list. If it is a set, the we do {} instead of []

cars=[]

Or straight away add some values.

cars = ["Ford", "Volvo", "BMW"]

Use the len() method to return the length of an array (the number of elements in an array) or query.

x = len(cars)
3

This is similar to PHP and django count()

To show a value = BMW

print(cars[2])

To know the number 2 or position of the list

print(index.cars('BMW'))

To sort (similar to PHP)

cars.sort()
print(cars)

Looping to show all values

for x in cars:
  print(x)

You can use the append() method to add an element to an array.

cars.append("Honda") 

Removing Array Elements by pop or remove

cars.pop(1) #2nd element

cars.remove("Volvo")

For List filter and finding duplicates

For PHP array.

See also Show all rows in Django template.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data