Skip to content

Instantly share code, notes, and snippets.

@hygull
Created January 10, 2017 17:03
Show Gist options
  • Select an option

  • Save hygull/c76162d7f6c36832f58f4c7525bf017a to your computer and use it in GitHub Desktop.

Select an option

Save hygull/c76162d7f6c36832f58f4c7525bf017a to your computer and use it in GitHub Desktop.
list comprehesion created by hygull - https://repl.it/FFTh/5
"""
Coded on : 10 January 2017.
Aim : Short hand notation for creating list in Python (3 examples)
Python version : 2.7.10
"""
#To create a list of lists each list denoting a table of numbers in range [1...10] one after one
tables=[[i*j for j in range(1,11)] for i in range(1,11)]
for lst in tables:
for num in lst:
print num,"\t",
print "\n"
#To create a list of even numbers that exist in range [1...20]
evens_list=[even for even in range(1,21) if even%2==0]
print evens_list
print "\n"
#To remove 0 entries from list
nums_list=[2,4,0,12,34,4,0,1,7,0,2,-6,0,-23,0]
print "Before removing the 0 entries"
print nums_list
l = [num for num in nums_list if num]
print "After removing the 0 entries"
print l
""" OUTPUT
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Before removing the 0 entries
[2, 4, 0, 12, 34, 4, 0, 1, 7, 0, 2, -6, 0, -23, 0]
After removing the 0 entries
[2, 4, 12, 34, 4, 1, 7, 2, -6, -23]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment