Python - Advanced list.

 

Python - Advanced  list.


LIST COMPREHENSIONS

  1. It is used to create a new list from the existing list.
  2. It consists of a bracket followed by a for loop than if (optional).
  3. 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.



Using list Comprehensions
  • 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.


Example - 2 Guess the output.

l = ['a', 'b', 'c'
l = [ i for i in l if ord(i) > 97]
print(l)




The del Operator.

  1. del operator stands for Delete.
  2. Used to Delete or remove  multiple element from a list.
  3. Used to Delete entire list .
  4. It's accessed element of list using the index position.
  5. 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 - 2 Remove elements from index position 2 to 5.

 

Example - 3 Delete the entire list.


LIST and FUNCTIONS.

  1. 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.


If you want to print the output in a single line use print(ele, end = " " )

Convert string to list.

  1. A list is a sequence of a values, but a string is a sequence of characters.
  2. To convert a string to list, use list() constructor.

Example - 1 Convert string to list.



Comments