It's usually used to mean "to be filled in later".
def fun():
pass
# ellipeses
# Supported in Python 3
def fun():
...
# Another usage of ellipeses
x = ... # alternative to None
x
Ellipsis
# Without else
found = False
x = "spam"
while x and not found:
if x[0] == "b":
print("Found")
found = True
else:
x = x[1:]
if not found:
print("Not found")
Not found
# With else
x = "spam"
while x:
if x[0] == "b":
print("Found")
break
x = x[1:]
else:
print("Not found")
Not found
D = {1: "a", 2: "b", 3: "c"}
for key, value in D.items():
print("Key: ", key, " Value: ", value)
Key: 1 Value: a Key: 2 Value: b Key: 3 Value: c
for a, *b, c in [(1, 2), (3, 4, 5, 6)]:
print(a, b, c)
1 [] 2 3 [4, 5] 6
read, readlines load a file all at once.
The following method might be *the best option for text files*.
It's usually the quickest way.
It uses iterator which doesn't load the entire file into memory all at once.
# Using iterator
for line in open("test.txt"):
print(line)
123456789 234567891 345687912 456789123
readlines can still be useful when reversing a file
for line in reversed(open("test.txt").readlines()):
print(line)
456789123 345687912 234567891 123456789
Use for instead of while whenever possible since it's usually quicker and easier.
In Python2 range returns a list while it returns iterator in Python3
In most case, range should not be used in for and they can be replaced by using iterator.
This would make your code more efficient.
s = "spam"
# range
for i in range(len(s)):
print(s[i])
# iterator
for i in s:
print(i)
s p a m s p a m
# range
L = [1, 2, 3, 4, 5]
for i in range(len(L)):
L[i] += 1
L
[2, 3, 4, 5, 6]
# comprehension
L = [1, 2, 3, 4, 5]
L = [x + 1 for x in L]
L
[2, 3, 4, 5, 6]
zip allow multiple sequences work in the same loop (not overlapping in time)
zip returns a list in Python2 and returns an iterator in Python3
L1 = [1, 2, 3, 4]
L2 = [5, 6, 7, 8]
list(zip(L1, L2))
# In fact, N arguments can be used and we'll get N-ary tuple
[(1, 5), (2, 6), (3, 7), (4, 8)]
zip truncates result tuples at the length of the shortest sequence
L1 = [1, 2]
L2 = [3, 4, 5, 6]
list(zip(L1, L2))
[(1, 3), (2, 4)]
key = [1, 2, 3]
value = "abc"
D = dict(zip(key, value))
D
{1: 'a', 2: 'b', 3: 'c'}
enumerate returns a gernerator object
s = "abcdefghijk"
for offset, item in enumerate(s, 1):
print(offset, item)
1 a 2 b 3 c 4 d 5 e 6 f 7 g 8 h 9 i 10 j 11 k