Tuesday, December 12, 2017

Lists in Python

So Lists,some time we want to form multiple objects under a single variable name.To define a list in python.you have to do something like this.

eg:
student_names = []

simple you have created empty student names list.if you want to add some student names then simple replace empty brackets like this

student_names = ["Abhinaw", "Rajat', "Gaurav", "Babli"]

now our list has 4 string elements.In order to access the names from list we use something called index staring from 0.
eg:

student_names[0] == "Abhinaw"
student_names[2] == "Gaurav"

So suppose you want to get last element from the list.then you have to do something like this.

student_names[-1] == "Babli"

So actually this gives the first element from right side of the list.In Python just remember there is no such thing negative zero.

                  List Functions

suppose you want add some names to list then you have to do like this.

eg:

student_names = ["Abhinaw", "rajat", "Gaurav"]

student_names[3] = "Babli" # No can do!

student_names.append("Babli") # Add to the  end

So now list will be:

student_names == ["Abhinaw", "rajat", "Gaurav", "Babli"]

*if you want to check the name already exist or not

eg:

"Abhinaw" in student_names == True

# Abhinaw is still there

*check how many elements in the list
eg:

len(student_list) == 4

Note: if you have noticed in Python we have never tell that it is list of string.So this is added advantage with the Python over other programming language.

    Delete element from List

eg:

students_names = ["abhinaw", "rajat", "Gaurav"]

del student_names[2]

this will delete 2nd element from list
which is "Gaurav" .Now the whole list will be going to shift after this operation.

                       List Slicing

student_names = ["Mark" ,"Katarina" ,"Homer"]

let say we want to ignore the first element which is "Mark" and get all other.

student_names[1:] == ["Katarina", "Homer"]

student_names[1:-1] == ["Katarina"]
Note this will not modify the list.list will be same it is just a temporary ignoring certain elements.

there are many more operations you can perform like reverse and pop etc.




No comments: