Today we will be talking on python list. As we earlier saw in python arrays, a list is an input data-type that can hold one data type or a combination of several data type. They are created with the use of square brackets and commas to separate the items within it.
Syntax for a python list
My list=[]
Some examples of python list are
Num_list=[0,5,10,25]
String_list[“cat”, “dog”, ”lion”]
Nested _list=[“keboard”,8,5,9[5,6,1]]
Accessing elements in a python list
They are several methods in accessing elements in a python list, most of which have been mentioned in python array under built-in functions. In addition to what we have seen so far, we are going to see some important ways of accessing elements in a python list.
Changing elements in a list
You can change an item or a range of items in a list with the use of assignment operator(=) and the indexing operator[].
Example:
even=[1,3,5,7,9]
even[0]=2
print(even)
OUTPUT
In this case we are going to add two lists, using the python +operator.
Example:
animals=['dog','cat','hen']
babies=['puppy','kitchen','chicks']
print(animals+babies)
OUTPUT
Example
abc=['a','b','c']*3
print(abc)
OUTPUT
This is different from the append () method that we learned earlier. In this method, you will learn how to insert an item on your desired location with the insert() method
Here’s the syntax for the insert() method
List.insert(index,obj)
Index: where the object ‘obj’ need to be inserted
Obj: this is the object to be inserted into the given list
Example
numbers=[1,2,4,6,8,10]
numbers.insert(2,3)
print(numbers)
In the case given, we want to insert 3 before 2, so we have to put 2 before 3, as the compiler will run it as 2 before of 3
OUPUT
These are mostly operators which are found on a list and are of two types “in” and “not in”. After the evaluation, the compiler returns the results as true or false. Here are examples in integers.
my_numbers=[1,2,5,7,36,48,]
print(7 in my_numbers)
print(14 in my_numbers)
OUTPUT
It is a way of creating a new list from an existing list. It is made up of an expression and a for ‘for statement’ enclosed in a square brackets. To illustrate, here is an example of creating a list where each item is an increasing power of 3.
pow3=[3**y for y in range(6)]
print(pow3)
OUPUT
Comments
Post a Comment
Please do not enter any spam link in the comment box.