What is List in a Python?
List is a collection of elements like a array in C, C++. But array contains all elements of same type, while in a list its not compulsory to have same type of elements.
How to create a List?
list_name=list()
Ex. a=list()
or
list_name=[element-1, element-2,....]
Ex. a=[1, 3.14, "Python"]
How to access the elements of a List?
In Python, list elements can be accessed by indexing. Index value can be integer (Positive or Negative).
Let a be the list containing five elements:
a=[10,20,30,40,50]
If we print a[0], it will display first number i.e. 10.
For a[2], it will display 30.
If we pass negative value as -1 i.e a[-1], it will display last number (50).
For accessing second last element, put a[-2].
Note:
Negative indexing starts from Left to Right.
Program
The following program will print the number as given position.
#Program: To read specific elements from a list
#Author: Hitendra E. Suryavanshi
a=[int(x) for x in input("Enter the numbers:").split()]
pos=int(input("Enter position to access number:"))
print("The No. is :",a[pos])
Output-1:
Output-2:
Thank You
Hitendra E. Suryavanshi
M.Tech.(IT), BE (IT)
List is a collection of elements like a array in C, C++. But array contains all elements of same type, while in a list its not compulsory to have same type of elements.
How to create a List?
list_name=list()
Ex. a=list()
or
list_name=[element-1, element-2,....]
Ex. a=[1, 3.14, "Python"]
How to access the elements of a List?
In Python, list elements can be accessed by indexing. Index value can be integer (Positive or Negative).
Let a be the list containing five elements:
a=[10,20,30,40,50]
If we print a[0], it will display first number i.e. 10.
For a[2], it will display 30.
If we pass negative value as -1 i.e a[-1], it will display last number (50).
For accessing second last element, put a[-2].
Note:
Negative indexing starts from Left to Right.
Program
The following program will print the number as given position.
#Program: To read specific elements from a list
#Author: Hitendra E. Suryavanshi
a=[int(x) for x in input("Enter the numbers:").split()]
pos=int(input("Enter position to access number:"))
print("The No. is :",a[pos])
Output-1:
Enter the numbers:10 20 30 40 50 Enter position to access number:2 The No. is : 30
Output-2:
Enter the numbers:10 20 30 40 50 Enter position to access number:-1 The No. is : 50
Thank You
Hitendra E. Suryavanshi
M.Tech.(IT), BE (IT)
No comments:
Post a Comment