Python list:
Python List 1 is similar to the goods in the domestic list. Objects of different data types can be placed inside it. Its syntax uses square brackets. Indexing and slicing can also be done like a string in the list. Below we will see some examples of Python lists.
animal_list1 = [‘cat’, ‘dog’, ‘horse’, ‘cow’]
bird_list = [‘peacock’, ‘crow’]
Like a string, the len() function can also be used in a Python list. Using this function, we can find out how many objects are inside a list. As explained in the example below.
only(animal_list1)
>> 4
Below we’ll see an example of Python indexing on the created animal_list. We printed the index zero of the animal_list.
print(animal_list[0])
>> cat
We can also create a list by combining two different lists. It is also called a concat operation.
combined_list = animal_list + bird_list
print(combined_list)
>> ‘ cat’, ‘dog’, ‘horse’, ‘cow’, ‘peacock’, ‘crow’
We can change the individual elements of the list. As in the example below, we have substituted index1 with ‘ostrich’.
bird_list[1] = ‘ostrich’
print(bird_list)
>> ‘peacock’, ‘ostrich’
Apart from this, if we want to add a new element at the end of the list, then there is a belt in function in Python. The name of this function is append.
bird_list.append(‘parrot’)
print(bird_list)
>> ‘peacock’, ‘ostrich’,’parrot’
The opposite function of the appendis the corresponding function: pop().
With the help of pop function, elements present in a Python list can be removed. We can give the pop(index) function the argument for which index element we have to remove
In the example below, we removed the index one object of the bird_list using the POP function. As we saw above, bird_list had an ‘ostrich’ value on index1. Therefore, ‘Ostrich’ will be removed.
reduced_list = bird_list.pop(1)
print(bird_list)
>> ‘peacock’,’ostrich’
Recent Comments