Python - List Questions Flashcards
a = [1,2,3,4,5,6,7,8]
a[1:4]
a = [1,2,3,4,5,6,7,8]
a[1:4]
returns [2,3,4]
indexes at 0 and does NOT include the last index
a = [1,2,3,4,5,6,7,8]
a[1:4:2]
a = [1,2,3,4,5,6,7,8]
a[1:4:2]
returns [2, 4]
slices along increments of 2 starting at your first index listed
a = [1,2,3,4,5,6,7,8]
a[ : : -1]
a = [1,2,3,4,5,6,7,8]
a[ : : -1]
returns [8, 7, 6, 5, 4, 3, 2, 1]
slices the list in reverse
a = [1, 2, 3, 4, 5]
sliceObj = slice(1, 3)
a[sliceObj]
a = [1, 2, 3, 4, 5]
sliceObj = slice(1, 3)
a[sliceObj]
return [2, 3]
lst = [x ** 2 for x in range (1, 11) if x % 2 == 1]
lst = [x ** 2 for x in range (1, 11) if x % 2 == 1]
x ** 2 is output expression,
range (1, 11) is input sequence,
x is variable and
if x % 2 == 1 is predicate part.
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print odd_square
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print odd_square
list contains square of all odd numbers from range 1 to 10
power_of_2 = [2 ** x for x in range(1, 9)]
print power_of_2
power_of_2 = [2 ** x for x in range(1, 9)]
print power_of_2
list contains power of 2 from 1 to 8
noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
primes = [x for x in range(2, 50) if x not in noprimes]
print primes
list contains prime and non-prime in range 1 to 50
noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
primes = [x for x in range(2, 50) if x not in noprimes]
print primes
print [x.lower() for x in [“A”, “B”, “C”]]
print [x.lower() for x in [“A”, “B”, “C”]]
list for lowering the characters
string = “my phone number is : 11122 !!”
print(“\nExtracted digits”)
numbers = [x for x in string if x.isdigit()]
print numbers
string = “my phone number is : 11122 !!”
print(“\nExtracted digits”)
numbers = [x for x in string if x.isdigit()]
print numbers
list which extracts number
a = 5 table = [[a, b, a * b] for b in range(1, 11)]
print(“\nMultiplication Table”)
for i in table:
print i
a = 5 table = [[a, b, a * b] for b in range(1, 11)]
print(“\nMultiplication Table”)
for i in table:
print i
A list of list for multiplication table
lst = filter(lambda x : x % 2 == 1, range(1, 20))
print lst
# filtering odd numbers lst = filter(lambda x : x % 2 == 1, range(1, 20)) print lst
We can use FILTER function to filter a list based on some condition provided as a ___________ as first argument and list as second argument.
We can use FILTER function to filter a list based on some condition provided as a ___________ as first argument and list as second argument.
lambda expression
lst = filter(lambda x : x % 5 == 0,
[x ** 2 for x in range(1, 11) if x % 2 == 1])
print lst
# filtering odd square which are divisble by 5 lst = filter(lambda x : x % 5 == 0, [x ** 2 for x in range(1, 11) if x % 2 == 1]) print lst
lst = filter((lambda x: x < 0), range(-5,5))
print lst
# filtering negative numbers lst = filter((lambda x: x < 0), range(-5,5)) print lst