Last active
August 29, 2015 14:03
-
-
Save smbanaie/0016b7b4503a721d2896 to your computer and use it in GitHub Desktop.
Some Python Code Imrovement TIPS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TIP #1 : Check Membership Efficiently | |
lyrics_list = ['her', 'name', 'is', 'rio'] | |
# Avoid this | |
words = make_wordlist() # Pretend this returns many words that we want to test | |
for word in words: | |
if word in lyrics_list: # Linear time | |
print word, "is in the lyrics" | |
# Do this | |
lyrics_set = set(lyrics_list) # Linear time set construction | |
words = make_wordlist() # Pretend this returns many words that we want to test | |
for word in words: | |
if word in lyrics_set: # Constant time | |
print word, "is in the lyrics" | |
TIP #2 : USE List comprehension Properly | |
words = ['her', 'name', 'is', 'rio'] | |
letters = [letter for word in words | |
for letter in word] | |
TIP #3 : Needing the index value in the loop | |
for index, value in enumerate(alist): | |
print index, value | |
TIP #4 : Needing to iterate over two loops at once, getting a value at the same index from each. | |
for word, number in zip(words, numbers): | |
print word, number | |
TIP #5 : Use xrange Instead Of range in case of Large List Iteration | |
This function is very similar to range(), but returns an xrange object instead of a list. | |
This is an opaque sequence type which yields the same values as the corresponding list, | |
without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() | |
still has to create the values when asked for them) except when a very large range is used on a memory-starved machine | |
or when all of the range’s elements are never used | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment