Introduction to Python Flashcards

Introduction to Python

1
Q

What is Print?

A

print () - built-in function that displays input values as text in the output

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are Arithmetic operators?

A

Arithmetic Operators

+ Addition
- Subtraction
* Multiplication
/ Division
% Mod (the remainder after dividing)
** Exponentiation (note that ^ does not do this operation, as you might have seen in other languages)
// Divides and rounds down to the nearest integer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is PEDMAS?

A

PEMDAS: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the type function?

A

it can be used to check the data type of any variable you are working with.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what is len() function?

A

len() is a built-in Python function that returns the length of an object, like a string. The length of a string is the number of characters in the string. This will always be an integer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what are String Methods?

A

len(“this”)
type(12)
print(“Hello world”)
sample_string.lower()
my_string.islower() - does not accept another argument.
my_string.count(‘a’)
my_string.find(‘a’) - both take another argument
print(“Mohammed has {} balloons”.format(27)
print(“Does your {} {}?”.format(animal, action))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what is F-String Formatting?

A

F-strings provide a concise and convenient way to embed expressions inside string literals, using curly brackets {}. The expressions will be replaced with their values when the string is evaluated.
a = 5
b = 3
print(f”The sum of {a} and {b} is {a+b}”)

name = “John”
print(f”Hello, {name}”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is String Method - Split?

A

The split method has two arguments (sep and maxsplit).
The sep argument stands for “separator”. It can be used to identify how the string should be split up (e.g., whitespace characters like space, tab, return, newline; specific punctuation (e.g., comma, dashes)).
If the sep argument is not provided, the default separator is whitespace.

True to its name, the maxsplit argument provides the maximum number of splits. The argument gives maxsplit + 1 number of elements in the new list, with the remaining string being returned as the last element in the list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Examples for split method

A

new_str = “The cow jumped over the moon.”
new_str.split()
[‘The’, ‘cow’, ‘jumped’, ‘over’, ‘the’, ‘moon.’]

new_str.split(‘ ‘, 3)
[‘The’, ‘cow’, ‘jumped’, ‘over the moon.’]

new_str.split(‘.’)
[‘The cow jumped over the moon’, ‘’]

new_str.split(None, 3)

[‘The’, ‘cow’, ‘jumped’, ‘over the moon.’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you find the length, first, last and count occurrence of word from string?

A

length = len(verse)
first_idx = verse.find(‘and’)
last_idx = verse.rfind(‘you’)
count = verse.count(‘you’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What Are Data Structures?

A

Data structures are containers or collections of data that organize and group data types together in different ways. You can think of data structures as file folders that have organized files of data inside them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are Lists?

A

list is one of the most common and basic data structures in Python.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you create List?

A

create a list with square brackets.

Lists can contain any mix and match of the data types you have seen so far.

list_of_random_things = [1, 3.4, ‘a string’, True]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Are lists Ordered?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Are lists Mutable?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Slice and Dice with Lists?

A

using slicing, it is important to remember that
the lower index is inclusive and
the upper index is exclusive

This type of indexing works exactly the same on strings, where the returned value will be a string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are Membership Operators?

A

in ==> evaluates if an element exists within our list
not in ==> evaluates if an element does not exist within our list

> > > 5 not in [1, 2, 3, 4, 6]
True
5 in [1, 2, 3, 4, 6]
False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Mutability?

A

Mutability refers to whether or not we can change an object once it has been created. If an object can be changed, it is called mutable. However, if an object cannot be changed after it has been created, then the object is considered immutable.

Examples - Lists are mutable, and strings are immutable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Ordered?

A

Order is about whether the position of an element in the object can be used to access the element. Both strings and lists are ordered. We can use the order to access parts of a list and string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Useful Functions for Lists?

A

len() returns how many elements are in a list.
max() returns the greatest element of the list.
max() function is undefined for lists that contain elements from different, incomparable types.
min() returns the smallest element in a list.
sorted() returns a copy of a list in order from smallest to largest, leaving the list unchanged.
append method
A helpful method called append adds an element to the end of a list.

21
Q

What is join method in List

A

Join is a string method that takes a list of strings as an argument, and returns a string consisting of the list elements joined by a separator string.

new_str = “\n”.join([“fore”, “aft”, “starboard”, “port”])
print(new_str)
Output:
fore
aft
starboard
port

name = “-“.join([“García”, “O’Kelly”, “Davis”])
print(name)
Output:
García-O’Kelly-Davis

22
Q

What are Tuples?

A

A tuple is another useful container. It’s a data type for immutable ordered sequences of elements. They are often used to store related pieces of information.

23
Q

How Tuples can be created?

A

Tupes can be created using brackets ()
location = (13.4125, 103.866667)
The parentheses are optional when defining tuples, and programmers frequently omit them if parentheses don’t clarify the code.
dimensions = 52, 40, 100

24
Q

How Tuples are accessed?

A

Tuples are similar to lists in that they store an ordered collection of objects which can be accessed by their indices.

25
Q

Are Tuples mutable?

A

tuples are immutable - you can’t add and remove items from tuples, or sort them in place.

26
Q

what is tuple unpacking?

A

dimensions = 52, 40, 100
length, width, height = dimensions
print(“The dimensions are {} x {} x {}”.format(length, width, height))

In the second line, three variables are assigned from the content of the tuple dimensions. This is called tuple unpacking. You can use tuple unpacking to assign the information from a tuple into multiple variables without having to access them one by one and make multiple assignment statements.

27
Q

What are Sets?

A

A set is a data type for mutable unordered collections of unique elements.

28
Q

Does set has duplicate elements?

A

No
numbers = [99, 100, 1, 3, 4, 99, 100]
unique_nums = set(numbers)
print(unique_nums)

Output
{1, 3, 99, 100, 4}

29
Q

How a set is defined?

A

using curly braces { }

30
Q

What are methods in sets?

A

add elements to sets using the add method, remove elements using the pop method
Note: pop an element from a set, a random element is removed.

31
Q

are set is ordered?

A

No Set is unordered.

32
Q

How do you perform union on list or set?

A

Sample data
set1 = set(range(1000))
set2 = set(range(500, 1500))
list1 = list(set1)
list2 = list(set2)

Union
start_time = time.time()
union_set = set1.union(set2)

start_time = time.time()
union_list = list(set(list1 + list2))

33
Q

How do you perform Intersection on sets and lists?

A

intersection_set = set1.intersection(set2)

intersection_list = [x for x in list1 if x in set2]

34
Q

How do you find difference on set or lists?

A

difference_set = set1.difference(set2)

difference_list = [x for x in list1 if x not in set2]

35
Q

operations performed on set objects are significantly faster than those on list objects?

A

Yes.

36
Q

what are dictionaries?

A

A dictionary is a mutable data type that stores mappings of unique keys to values.

In general, dictionaries look like key-value pairs, separated by commas:

{key1:value1, key2:value2, key3:value3, key4:value4, …}

37
Q

How dictionaries are created?

A

Using curly braces { }

38
Q

In python does only dictionaries are created using the curly braces?

A

No.
Both Set and dictionaries are created using the same curly braces { }

39
Q

Are dictionaries mutable?

A

Yes.
Key part is immutable.
Value part is mutable.

40
Q

How can we access the dictionary elements?

A

Using the key value passed using the Square brackets
elements = {“hydrogen”: 1, “helium”: 2, “carbon”: 6}
print(elements[“helium”])
Alternatively,
print(elements.get(“helium”))
unlike square brackets will give you a “KeyError”, get returns None (or a default value of your choice) if the key isn’t found.

41
Q

Can we use in and not in for dictionaries elements?

A

Yes.

print(“carbon” in elements)

42
Q

what are Identity Operators?

A

is ==> evaluates if both sides have the same identity
is not ==> evaluates if both sides have different identities

n = elements.get(“dilithium”)
print(n is None)
print(n is not None)

output:
True
False

43
Q

what are Compound Data Structures?

A

include containers in other containers to create compound data structures. For example, this dictionary maps keys to values that are also dictionaries!

We can access elements in this nested dictionary like this.

44
Q

What is zip?

A

zip returns an iterator that combines multiple iterables into one sequence of tuples. Each tuple contains the elements in that position from all the iterables.
For example, printing

list(zip([‘a’, ‘b’, ‘c’],
[1, 2, 3]))
would output
[(‘a’, 1), (‘b’, 2), (‘c’, 3)].

for letter, num in zip(letters, nums):
print(“{}: {}”.format(letter, num))

45
Q

what is unzipping?

A

exactly opposite of zip.
unzip a list into tuples using an asterisk.

some_list =
[(‘a’, 1), (‘b’, 2), (‘c’, 3)]
letters, nums = zip(*some_list)

46
Q

what is enumerate?

A

enumerate is a built in function that returns an iterator of tuples containing indices and values of a list. You’ll often use this when you want the index along with each element of an iterable in a loop.

letters =
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
for i, letter in enumerate(letters):
print(i, letter)
output:
0 a
1 b
2 c
3 d
4 e

47
Q

what is List Comprehensions?

A

List comprehensions allow us to create a list using a for loop in one step.

You create a list comprehension with brackets [].

48
Q

How the list comprehension works?

A

capitalized_cities = []
for city in cities: capitalized_cities.append(city.title())

can be reduced to:
capitalized_cities = [city.title() for city in cities]

49
Q

Can we use Conditionals in List Comprehensions?

A

After the iterable, you can use the if keyword to check a condition in each iteration.

squares = [x**2 for x in range(9) if x % 2 == 0] sets squares equal to the list [0, 4, 16, 36, 64], as x to the power of 2 is only evaluated if x is even.
==> Here if acts as a filter of the for-loop.

If you would like to add else, you have to move the conditionals to the beginning of the listcomp, right after the expression, like this.

squares = [x**2 if x % 2 == 0 else x + 3 for x in range(9)]

==> Here if acts as a conditional expression of the for-loop.