Python Array
26/4
## Python Array[ ]
- Collection of similar elements is called array.
## Types of Array Separator:-
1. comma(,) is called variable separator.
2. { } block separator used in looping and condition
3. ( ) function separator
4. [ ] array separator
example:-
car = ["maruti","indica","swift"]
print(car)
output:- ['maruti', 'indica', 'swift']
## Access array elements
car = ["maruti","indica","swift"]
x = car[0]
print(x)
output:- maruti
## Modify array element
car = ["maruti","indica","swift"]
car[0] = "swiftD'zire"
print(car)
output:- ['swiftD'zire', 'indica', 'swift']
## Find the length of array
car = ["maruti","indica","swift"]
x = len(car)
print(x)
output:- 3
## Using for loop in array concept
car = ["maruti","indica","swift"]
for x in car:
print(x)
output:-
maruti
indica
swift
## Adding new element in array
car = ["maruti","indica","swift"]
car.append("honda")
print(car)
output:- ["maruti","indica","swift","honda"]
## How to remove array element
car = ["maruti","indica","swift"]
car.pop(1)
print(car)
output:- ["maruti","swift"]
## Remove array element with name
car = ["maruti","indica","swift"]
car.remove("swift")
print(car)
output:- ["maruti","indica"]
## Sort array element
car = ["maruti","indica","swift"]
car.sort()
print(car)
output:- ['indica', 'maruti', 'swift']
## Reverse array element
car = ["maruti","indica","swift"]
car.reverse()
print(car)
output:- ['swift', 'indica', 'maruti']
## Count array element
car = ["maruti","indica","swift","maruti"]
x = car.count("maruti")
print(x)
output:- 2 (bcoz here maruti is written 2 times)
## Copy array element
car = ["maruti","indica","swift","maruti"]
x = car.copy()
print(x)
output:- ['maruti', 'indica', 'swift', 'maruti']
## Insert array element
car = ["maruti","indica","swift","maruti"]
car.insert(1,"honda")
print(car)
output:- ['maruti', 'honda', 'indica', 'swift', 'maruti']
## Clear the array element
car = ["maruti","indica","swift","maruti"]
car.clear()
print(car)
output:- [ ]
## User input array
listA = [ ]
n = int(input("enter the no. of element"))
for i in range(0,n):
print("enter element")
ele = int(input())
listA.append(ele)
print("the element of list A \n ", listA)
output:- enter the no. of element 4
4
enter element
3
enter element
6
enter element
2
enter element
5
the element of list A
[3, 6, 2, 5]
example:-
toys = [ ]
n = int(input("enter the no. of toys "))
for i in range(0,n):
print("toy position")
num = int(input())
toys.append(num)
print("list of toys are \n ", toys)
output:-
enter the no. of toys 6
toy position
5
toy position
8
toy position
2
toy position
5
toy position
9
toy position
4
list of toys are
[5, 8, 2, 5, 9, 4]
Task:- WAP to input 5 no. user choice and store the array
(here we've fixed the range that is why it'll take upto 5 no. only)
Comments
Post a Comment