List in Python


 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 : 

  1. x1 = ["John"102"USA"]    
  2. x2 = [123456]   


If we try to print the type of x1 and x2 using type() function then it will come out to be a list.

  1. print(type(x1))  
  2. print(type(x2))  


Output :

<class 'list'>
<class 'list'>

Example :
  # creating a blank list
      list=[]
      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 :
  1. list = [1,2,3,4,5,6,7]  
  2. print(list[0])  
  3. print(list[1])  
  4. print(list[2])  
  5. print(list[3])  
  6. # Slicing the elements  
  7. print(list[0:6])  
  8. # print the complete list  
  9. print(list[:])  
  10. print(list[2:5])  
  11.  

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