OCJP

Array in Python

As Array in a collection of Variables with same name, in python we can use like:

subjects = ["English", "Maths", "Science","History"]

#Print Array
print(subjects)

#Using for Loop
for sub in subjects:
    print(sub)

#Using Index i
print("Array Iteration using Index")
for i in range(len(subjects)):
    print(subjects[i])

#Modify  Array Value
subjects[2]="Social Science"
print(subjects)


#subjects[4]="Computer" #Will Generate error as there are only 4 vals in Array
#print(subjects)

subjects.append("Computer")  # Will add at last
print(subjects)

subjects.insert(2,"Hindi")  # will insert at 3rd position
print(subjects)


subjects.remove("Maths") #Errr if no value is present in array
print(subjects)


subjects.pop(3) # Will Remove 4th element
print(subjects)


othersub=["French","Environment Science"]
subjects.extend(othersub) # add values from another array
print(subjects)


subjects.reverse() #As name suggest it reverse the array
print(subjects)

subjects.sort()
print(subjects)

subjects.sort(reverse=True) #Desending Order
print(subjects)


subjects.clear() # Clear all
print(subjects)

Output for the same will be

['English', 'Maths', 'Science', 'History']
English
Maths
Science
History
Array Iteration using Index
English
Maths
Science
History
['English', 'Maths', 'Social Science', 'History']
['English', 'Maths', 'Social Science', 'History', 'Computer']
['English', 'Maths', 'Hindi', 'Social Science', 'History', 'Computer']
['English', 'Hindi', 'Social Science', 'History', 'Computer']
['English', 'Hindi', 'Social Science', 'Computer']
['English', 'Hindi', 'Social Science', 'Computer', 'French', 'Environment Science']
['Environment Science', 'French', 'Computer', 'Social Science', 'Hindi', 'English']
['Computer', 'English', 'Environment Science', 'French', 'Hindi', 'Social Science']
['Social Science', 'Hindi', 'French', 'Environment Science', 'English', 'Computer']
[]

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?