Python Lists
It is a collection of data type used to store values.
In python different types of collection data types which is given below:
-
List
-
Tuple
-
Set
-
Dictionary
Python lists are written within square brackets.
Python lists are declared a simple way –
>>> li = [ ]
Adding elements to the list
If anyone wants to add the element to the list then use append().
>>> li.append(5)
Accessing Element From the list
You can easily access elements from list using index as per given example.
>>> li[2]
Where 5 is the index value, it starts from 0.
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.
Selecting element using range index
>>> li = [1,2,3,4,5]
>>> li[2:5]
Selecting element using negative range index
>>> li[-2:-4]
Update list value
>>> li[1] = 5
It updates value 5 at 1 index.
Length of list
Length of list can be found using len() function
>>> len(li)
Removing item from lists
We can remove the item from list using remove() method as-
It removes the specified item from the list
>>> li.remove[2]
it removes 2 value-form lists.
Using del method
It deletes element as per index value.
>>> del li #it delete complete list
>>> del li[2] #delete second index elements
Using clear() method
It used to empty the list.
Copy the list
We can copy the list using a copy() method and save it into another variable.
Join lists
List can be join using plus(+) symbol.
Creating list using list() constructor
You can create list using list constructor by using elements inside the double rounded brackets.
>>> List = list((“welcome”, “to”, “the”, “codersarts”))
Thanks for reading this tutorial, in next we will learn all about the "python tuples"