• Tutorials Logic, IN
  • +91 8092939553
  • info@tutorialslogic.com

Python Lists

Lists

List is implemented to store the sequence of various type of data. List is the most generic data type in Python programming language. Lists can consist of an ordered collection of mixed data types, separated by commas and enclosed within square brackets ([ ]).

Creating a List:- A list can be created easily by putting the value inside the square bracket (i.e. [ ]), and values are separated by commas.

										    
											# A empty list
											list = []
											
											# A list of integers
											list = [1, 2, 3]
											
											# A list of strings
											list = ['apple', 'banana', 'mango']
											
											# A list with mixed datatypes
											list = [1, "hello", 3.4]
											
										

Accessing Elements from a List:- There are various ways to access an element from the Python list, which are given below-

Using List Index:- We can easily access an element from the list using index, which starts from zero (0) and ends at the last index of a list.

										    
											list = [ 'apple', 'banana', 'orange', 'grapes', 'jackfruit', 'mango' ]
											print(list[2]) # orange
											
										

Using Negative Indexing:- We can easily access an element from the list using negative index, which starts from -1 (i.e. last index of list) and ends at the beginning of a list (i.e. first index of a list).

										    
											list = [ 'apple', 'banana', 'orange', 'grapes', 'jackfruit', 'mango' ]
											print(list[-2]) # jackfruit
											
										

Using Index Range:- We can easily access range of an element from the list by providing the index range. If we miss the start value, the range will start from the zero (0), and if we miss the last value, then the range will ends at the last index of a list.

										    
											list = [ 'apple', 'banana', 'orange', 'grapes', 'jackfruit', 'mango' ]
											print(list[1:3]) # ['banana', 'orange']
											
											list = [ 'apple', 'banana', 'orange', 'grapes', 'jackfruit', 'mango' ]
											print(list[:3]) # ['apple', 'banana', 'orange']
											
											list = [ 'apple', 'banana', 'orange', 'grapes', 'jackfruit', 'mango' ]
											print(list[1:]) # ['banana', 'orange', 'grapes', 'jackfruit', 'mango']
											
										

Updating a Lists:-

Deleting an Element from the List:-

Python List Methods:-

										    
											x = 5
											y = 2.5
											sum = x + y
											print(type(sum)) # float