List :
List are just like the arrays, declared in other languages. List not need be homogeneous always make it the most powerful tool in Python. A single list may contain different data types like integers, string as well as object. Lists are mutable, and hence they can change even after their creation. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 begin the first index. Its represented by list class.
List in Python can be created by just placing the sequence inside the square brackets [ ].
Example :
- x1 = ["John", 102, "USA"]
- x2 = [1, 2, 3, 4, 5, 6]
- print(type(x1))
- print(type(x2))
<class 'list'> <class 'list'>
Example :
# creating a blank listlist=[]
print("initial blank list:")
print(list)
# creating a list with the use of string
list=["btech"]
print("list with the use of string:")
print(list)
# creating a list with the use of multiple values
list=["btech","computer","science"]
print(list[0])
print(list[2])
Output :
initial blank list:
[]
list with the use of string:
[btech]
btech
science
List Indexing :
The indexing is processed in the same way as it happens with the strings. The elements of the list can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so on.
Let us understand by the following example :
- list = [1,2,3,4,5,6,7]
- print(list[0])
- print(list[1])
- print(list[2])
- print(list[3])
- # Slicing the elements
- print(list[0:6])
- # print the complete list
- print(list[:])
- print(list[2:5])
Output :
1 2 3 4 [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 7] [3, 4, 5]
No comments:
Post a Comment