Python - Advanced list.
Python - Advanced list.
LIST COMPREHENSIONS
- It is used to create a new list from the existing list.
- It consists of a bracket followed by a for loop than if (optional).
- It will make your code more pythongenic or optimal.
Syntax of list comprehensions.
[ expression for loop than if condition]
In layman language
[ return statement for loop followed by if condition (optional)]
Simple example :-
Now, writing this piece of code using list comprehension. It's easy guys stay on this page. If you are not able to understand just stay you will get it.
- The return one will come first.
- After that for loop will come.
- You don't have to give colon ":" symbol at the last.
- If there is an if condition between return and for loop it will come after the for loop in list comprehension. See the syntax you will get it.
Steps to create list comprehensions.
Now, we know it's consist of bracket. put the bracket first - []After bracket it will contain an expression means Ask yourself what you are returning. for this we are returning square of the element, So. It will be like bracket than return statement - [ i * i ]
Then, we know after return for loop will come -- [ i*i for i in lst]
You can also save this result into the another variable, cause it's return list.
That's all.
Example - 1 Write a program with the help of list comprehensions.
The del Operator.
- del operator stands for Delete.
- Used to Delete or remove multiple element from a list.
- Used to Delete entire list .
- It's accessed element of list using the index position.
- If the index is out of range. It gives the run time error.
Syntax of del Operator.
del list_variable[ pass the index of the element that you want to remove]
Example - 1 Remove the single element from a list.
Example - 3 Delete the entire list.
LIST and FUNCTIONS.
- We can change the content of a list after passing it to a function.
Example - Create a list of elements and pass it to the functions and print it with the help of function.
Convert string to list.
- A list is a sequence of a values, but a string is a sequence of characters.
- To convert a string to list, use list() constructor.
Comments
Post a Comment