Blog

Filter posts by Category Or Tag of the Blog section!

List Comprehensions in python

Saturday, 17 June 2017

I'm a Dot Net developer, but sometimes I jump on other programming languages and I think it helps me to comprehend my main field of activity easily. I was just working with the list in Python. Let's create a simple list:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
mylist = ["angular""javascript""typeScript"]
 
  
 
print(mylist)  ##For printing the list
 
   
 
for in mylist  ##For creating a loop through the list
 
  print(x)
 
  
 
print(len(mylist )) ##For getting the length of the list
 
  
 
mylist.append("backbon"##For adding an Item
 
  
 
mylist.Remove("javascript"##For removing an item
 
  
 
mylist.clear() ##For clearing the list
 
  
 
Del mylist  ##For deleting the whole list
 
  
 
mylist[1]   ##For getting the member of an index
 
  
 
mylist.Insert(4,"meteor")   ##For inserting an item to a specific index
 
  
 
mylist.Pop()   ##To removing the last member of the list
 
  
 
mylist.reverse()  ## for reversing the list

 

Python also supports negative indexes. For example, the index of -1 refers to the last item, -2 refers to the second last item etc.

 

1
print(Mylist[-2]) ## output:javascript

 

And it worth mentioning that, python supports for slice as well

 

1
2
3
4
5
6
7
8
9
10
print(mylist[1:3])   ## elements 1rd to 3th
 
  
 
print(mylist[:-3])  ## elements beginning to 2th
 
  
 
print(my_list[2:]) ## elements 3th to end
  

Category: Software

Tags: Python