Python List - index, slicing, append, del
- The list represents the collection data of different types.
- The data stored in the list are separated by comma.
- The whole list is enclosed by square bracket([]).
- Use the slice[:] operator to access data from the list.
- The * symbol is used for the repetition operator and, the + symbol is used as a concatenation operator.
Syntax for Python List
- We can declare the list by using the following syntax.
List_name = [initial values]
For example
Age =[ 24,45,67,23,30]
List_name = [ ]
Accessing items from the list
There are two ways to access the items from the list.
- By using the index value
- By using slice notation
By Using the Index Value
- We can access the individual value by using the index value.
- The index has a range from zero to size-1.
- The first item is stored on the index value 0, the second item is on index value 1, and so on.
For example:
Age [0]=24,Age[1]=45
Age [-1]=30,Age[-2]=23
By using Slice Notation
- Slicing allows us to access a part of the list by specifying the index range.
- Slicing specifies the start and end index value along with colon[:] operator.
- Following is the syntax
List_name[start:stop[:step]]
For example
>>user_Age_lists=[33,40,55,21,43]
>>user_Age_lists[1:4]
[40,55,21]
>>user_Age_lists[:4]
[33,40,55,21]
>>user_Age_lists[2:]
[55,21,43]
>>user_Age_lists[1:5:2]
[40,21]
>>
The list() Function
- The list() function is used to create the list.
- Following is the syntax.
List_Name(sequence)
For example
>>Message = "welcome"
>>List_name=list(Message)
['w','e','l','c','o','m','e']
>>
Modify items in a list
- The list is mutable, so We can modify items in the list by replacing old vale with new value.
- Following is the syntax to modify items in a list.
List_name[index of item to be modified]= new_value
For Example
>>fruits =['mango ',' fig',' banana']
>>fruits[1]= 'apple'
>>fruits
['mango',' apple',' banana']
>>
Add an item to the list
- We can add a new item to the list by using the append() function.
- For example, If we want to add fig to the Fruits list. we can execute the following code
>>fruits.append('fig')
>>
>>fruits
[ 'mango',' apple ',' banana',' fig']
>>
Remove items from the list
- We can remove the item from the list by using the del statement.
- Syntax of del statement is
del list_name[index of the item to be deleted]
>>del fruits[2]
>>
>>fruits
[ 'mango ',' apple ',' fig']
>>