Professional Documents
Culture Documents
List Comprehensions
Indexing and Slicing
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[-1]
'lobster'
>>> a[-2]
'ham'
>>> a[-5]
'egg'
>>> a[-6]
'spam'
>>> a[-len(a)]
'spam'
>>> a[2:5]
>>> a[-5:-2]
>>> a[1:4]
True
Omitting the first index a[:n] starts the slice at the beginning of the
list.
Omitting the last index a[m:] extends the slice from the first index m to
the end of the list.
Omitting both indexes a[:] returns a copy of the entire list, but unlike
with a string, it’s a copy, not a reference to the same object.
>>> a
>>> a[:4]
>>> a[0:4]
>>> a[2:]
>>> a[2:len(a)]
>>> a
>>> a[:]
>>> a == a[:]
True
>>> a is a[:]
False
>>> s = 'mybacon'
>>> s[:]
'mybacon'
>>> s == s[:]
True
>>> s is s[:]
True
A stride can be added to your slice notation. Using an additional : and a
third index designates a stride (also called a step) in your slice notation. The
stride can be either postive or negative:
>>> a
>>> a[0:6:2]
>>> a[1:6:2]
>>> a[6:0:-2]
>>> a
>>> a[::-1]
List Comprehensions?
Iterable
Iterator variable which represents the members of the iterable
numbers=[1,2,3,4,5]
print(squares)
numbers = [1, 2, 3, 4, 5]
print(squares)
numbers = [1, 2, 3, 4, 5]
squares = []
if number > 2:
squares.append(number**2)
print(squares)
What about the computational speed? We can use the timeit library
to compare the speed of a for loop vs the speed of a list
comprehension. We can also pass the number of executions using
the number argument. We’ll set this argument to 1 million.
import timeit
def squares(size):
result = []
result.append(number*number)
return result
def squares_comprehension(size):
Lambda Functions
Map Function
# Map
numbers = [1, 2, 3, 4, 5]
print(squares)
# List Comprehension
numbers = [1, 2, 3, 4, 5]
print(squares)
Filter Function
# Filter
numbers = [1, 2, 3, 4, 5]
print(filtered)
# List Comprehension
numbers = [1, 2, 3, 4, 5]
print(filtered)
print(squares)
squares = ["small" if number < 10 else "big" for number in numbers if number % 2 == 0 if
number % 3 == 0]
print(squares)
Readability
We can see that some list comprehensions can be very complex and
it’s hard to read them. Python allows line breaks between brackets
and braces. We can use this to make our complex comprehension
more readable.For example, we can our last transform example to
this:
squares = [
if number % 2 == 0
if number % 3 == 0]
print(squares)
In some cases, we need nested for loops to complete some task. In this
cases, we can also use a list comprehension to achieve the same
result.
flattened = []
print(flattened)
print(flattened)
print(matrix)
Other Comprehensions
Dictionary Comprehensions
print(float_prices)
Set Comprehensions
print(unique_squares)
Differences between
List, Tuple, Set and
Dictionary in Python
List
Lists are one of the most commonly used data structures provided by
python; they are a collection of iterable, mutable and ordered data.
They can contain duplicate data.
Tuple
Tuples are similar to lists. This collection also has iterable, ordered,
and (can contain) repetitive data, just like lists. But unlike lists,
tuples are immutable.
Set
Dictionary
list2 = []
list3 = list((1,2,3))
print(list1)
print(list2)
# Output: [ ]
print(list3)
# Output: [1, 2, 3]
______________________________________________________________________
tuple1=(1,2,'abc', 3, 4)
tuple2=()
tuple3=tuple((1,3,5,"hello"))
print(tuple1)
print(tuple2)
# Output: () )
print(tuple3)
____________________________________________________________
set1={1,2,3,'abc', 6}
print(set1)
____________________________________________________________
dict1={"key1":"value1","key2":"value2"}
dict2={}
dict3=dict({1:"one",2:"two",3:"three"})
print(dict1)
print(dict2)
# Output: {}
print(dict3)
________________________________________________________________
print(list1[2])
_____________________________________________________________________
print(tuple1[2])
set1={1,2,3,4,5}
print(set1)
dict1={"one":1, "two": 2, "three": 3}
print(dict1.keys())
print(dict1.values())
# Output: [3, 2, 1]
print(dict1['two'])
# output: 2
________________________________________________________________________________
list1=["one","two","three"]
list1.append("four") print(list1)
___________________________________________________________________
set1.add("four") print(set1)
____________________________________________________________________________
dict1={"India":"IN","Russia":"RU","Australia":"AU"} dict1.update({"Canada":"CA"})
print(dict1)
dict1.pop("Australia") print(dict1)
________________________________________________________________________________
list1=["one","two","three", “four”]
list1.pop() print(list1)
list1.pop()
print(list1)
# output: ['one', 'two']
_____________________________________________________________
set1 = {"one","two","three"}
set1.pop()
print(set1)
_____________________________________________________________________
dict1={"India":"IN","Russia":"RU","Australia":"AU"}
dict1.pop('Russia') print(dict1)
___________________________________________________________________________
list1.sort()
print(list1)
print(list2)
________________________________________________________________________________
dict1={"India":"IN","Russia":"RU","Australia":"AU"}
print(sorted(dict1))
_________________________________________________________________________________
print(list1.index(4))
# output: 2
# output: 2
___________________________________________________________________
dict1={"India":"IN","Russia":"RU","Australia":"AU"} print(dict1['Australia'])
# Output: AU
___________________________________________________________________________
list1.reverse() print(list1)
________________________________________________________________
list1 = [1,2,3,6,2,2,2]
print(list1.count(2))
tuple1 = (1,2,3,6,2,2,2)
print(tuple1.count(2))