Arrays in Python
The idea of arrays comes from that we have multiple variables of the same type and we want to put them together like this
name1 = 'Ahmed'
name2 = 'Ali'
name3 = 'Manar'
We put them in one array called "names"
names = ['Ahmed','Ali','Manar']
Access the Elements of an Array
You refer to an array element by referring to the index number.
x = names[1]
print(x)
Ali
Modify a value in the array
names[0] = "John"
print(names)
['John', 'Ali', 'Manar']
The Length of an Array
Use the len() method to return the length of an array (the number of elements in an array).
x = len(names)
print(x)
3
Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
for i in names:
print(i)
John
Ali
Manar
Adding Array Elements
You can use the append() method to add an element to an array.
names.append("Hoda")
print(names)
['John', 'Ali', 'Manar', 'Hoda']
Removing Array Elements
You can use the remove() method to remove an element from the array.
names.remove("Hoda")
print(names)
['John', 'Ali', 'Manar']
You can refer to the code form here
Kommentare