Diving into the arena, and want to flex your Python muscles? These tips will help you rise up the scoreboard in no time!
(Note: This post is specific to Python3)
Input and Output Look no further than input() for all your input needs. Every call returns a string for a line in the standard input. However, you may need to convert your input to be able to use it in your program. int(input()) will return a numeric value for your input. input().split() will return a list (array) of strings, using whitespace as a default delimiter. Similarly, print(element1, element2) will suffice all your outputs.The keyword argument ‘sep’ determines what is printed between two arguments, while ‘end’ will help you control newline behaviour, among other things.
Sort and Search Depending on your needs, you may sort a list in place using list.sort(), or return a new list using sorted(list). (Tip: Read the Sorting guide for advanced sorting techniques such as key functions) For searching, use find(element), which returns the index of the element if element exists in the list, -1 otherwise. However, if index is trivial, you may use the 'in' operator. The expression element in list returns True if element is present in the list.
Data Structures Lists are python’s equivalent to arrays, and elements are accessed using numeric indices. Negative indices are used to access elements from the tail of the list. list[-n] returns the nth element from the end List[a:b] returns a sublist from index a (incl.) to b (excl.) Dictionaries store data as key:value pairs, and elements are accessed as dict[key]. Keys cannot duplicate in a single dictionary. Use dict.items() to iterate over a dictionary. Ex. for key, value in dict.items():
Bonus Use map(function, list) to apply a function to every element in the list. You can iterate over the result in a for loop as: for item in map(function, list):
However, if you want to access the result using indices, use list(map(f,l)).