DATA MANIPULATION - SOLOLEARN

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Strings Concatenation

As with integers and floats, strings in Python can be added, using a process called concatenation, which can be done on any two strings. When concatenating strings, it doesn't matter whether they've been created with single or double quotes. >>> "Spam" + 'eggs' 'Spameggs' >>> print("First string" + ", " + "second string") First string, second string Even if your strings contain numbers, they are still added as strings rather than integers. Adding a string to a number produces an error, as even though they might look similar, they are two different entities. >>> "2" + "2" '22' >>> 1 + '2' + 3 + '4' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'Try It Yourself In future lessons, only the final line of error messages will be displayed, as it is the only one that gives details about the type of error that has occurred.

Dictionaries

Dictionaries Dictionaries are data structures used to map arbitrary keys to values. Lists can be thought of as dictionaries with integer keys within a certain range. Dictionaries can be indexed in the same way as lists, using square brackets containing keys. Example: ages = {"Dave": 24, "Mary": 42, "John": 58} print(ages["Dave"]) print(ages["Mary"])Try It Yourself Result:>>> 24 42 >>> Each element in a dictionary is represented by a key:value pair. Dictionaries Trying to index a key that isn't part of the dictionary returns a KeyError. Example: primary = { "red": [255, 0, 0], "green": [0, 255, 0], "blue": [0, 0, 255], } print(primary["red"]) print(primary["yellow"])Try It Yourself Result:>>> [255, 0, 0] KeyError: 'yellow' >>> As you can see, a dictionary can store any types of data as values. An empty dictionary is defined as {}. Dictionaries Only immutable objects can be used as keys to dictionaries. Immutable objects are those that can't be changed. So far, the only mutable objects you've come across are lists and dictionaries. Trying to use a mutable object as a dictionary key causes a TypeError. bad_dict = { [1, 2, 3]: "one two three", }Try It Yourself Result:>>> TypeError: unhashable type: 'list' >>> Dictionaries Just like lists, dictionary keys can be assigned to different values. However, unlike lists, a new dictionary key can also be assigned a value, not just ones that already exist. squares = {1: 1, 2: 4, 3: "error", 4: 16,} squares[8] = 64 squares[3] = 9 print(squares)Try It Yourself Result:{8: 64, 1: 1, 2: 4, 3: 9, 4: 16} Dictionaries To determine whether a key is in a dictionary, you can use in and not in, just as you can for a list. Example: nums = { 1: "one", 2: "two", 3: "three", } print(1 in nums) print("three" in nums) print(4 not in nums) Try It Yourself Result: >>> True False True >>> Dictionaries A useful dictionary method is get. It does the same thing as indexing, but if the key is not found in the dictionary it returns another specified value instead ('None', by default). Example: pairs = {1: "apple", "orange": [2, 3, 4], True: False None: "True", } print(pairs.get("orange")) print(pairs.get(7)) print(pairs.get(12345, "not in dictionary"))Try It Yourself Result:>>> [2, 3, 4] None not in dictionary >>>

Strings in Python

If you want to use text in Python, you have to use a string. A string is created by entering text between two single or double quotation marks. When the Python console displays a string, it generally uses single quotes. The delimiter used for a string doesn't affect how it behaves in any way. >>> "Python is fun!" 'Python is fun!' >>> 'Always look on the bright side of life' 'Always look on the bright side of life' Some characters can't be directly included in a string. For instance, double quotes can't be directly included in a double quote string; this would cause it to end prematurely. Characters like these must be escaped by placing a backslash before them. Other common characters that must be escaped are newlines and backslashes. Double quotes only need to be escaped in double quote strings, and the same is true for single quote strings.>>> 'Brian\'s mother: He\'s not the Messiah. He\'s a very naughty boy!' 'Brian's mother: He's not the Messiah. He's a very naughty boy!' \n represents a new line. Backslashes can also be used to escape tabs, arbitrary Unicode characters, and various other things that can't be reliably printed. These characters are known as escape characters.

List Functions

List Functions Another way of altering lists is using the append method. This adds an item to the end of an existing list. nums = [1, 2, 3] nums.append(4) print(nums)Try It Yourself Result:>>> [1, 2, 3, 4] >>> The dot before append is there because it is a method of the list class. Methods will be explained in a later lesson. List Functions To get the number of items in a list, you can use the len function. nums = [1, 3, 5, 2, 4] print(len(nums))Try It Yourself Result:>>> 5 >>> Unlike append, len is a normal function, rather than a method. This means it is written before the list it is being called on, without a dot. List Functions The insert method is similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end. words = ["Python", "fun"] index = 1 words.insert(index, "is") print(words)Try It Yourself Result:>>> ['Python', 'is', 'fun'] >>> List Functions The index method finds the first occurrence of a list item and returns its index. If the item isn't in the list, it raises a ValueError. letters = ['p', 'q', 'r', 's', 'p', 'u'] print(letters.index('r')) print(letters.index('p')) print(letters.index('z'))Try It Yourself Result:>>> 2 0 ValueError: 'z' is not in list >>> There are a few more useful functions and methods for lists. max(list): Returns the list item with the maximum value min(list): Returns the list item with minimum value list.count(obj): Returns a count of how many times an item occurs in a list list.remove(obj): Removes an object from a list list.reverse(): Reverses objects in a list

Lists Operations

Lists Lists are another type of object in Python. They are used to store an indexed list of items. A list is created using square brackets with commas separating items. The certain item in the list can be accessed by using its index in square brackets. For example: words = ["Hello", "world", "!"] print(words[0]) print(words[1]) print(words[2])Try It Yourself Result:>>> Hello world ! >>> The first list item's index is 0, rather than 1, as might be expected. Lists An empty list is created with an empty pair of square brackets. empty_list = [] print(empty_list)Try It Yourself Result:>>> [] >>> Most of the time, a comma won't follow the last item in a list. However, it is perfectly valid to place one there, and it is encouraged in some cases. Lists Typically, a list will contain items of a single item type, but it is also possible to include several different types. Lists can also be nested within other lists. number = 3 things = ["string", 0, [1, 2, number], 4.56] print(things[1]) print(things[2]) print(things[2][2])Try It Yourself Result:>>> 0 [1, 2, 3] 3 >>> Lists of lists are often used to represent 2D grids, as Python lacks the multidimensional arrays that would be used for this in other languages. Lists Indexing out of the bounds of possible list values causes an IndexError. Some types, such as strings, can be indexed like lists. Indexing strings behaves as though you are indexing a list containing each character in the string. For other types, such as integers, indexing them isn't possible, and it causes a TypeError. str = "Hello world!" print(str[6])Try It Yourself Result:>>> w >>> List Operations The item at a certain index in a list can be reassigned. For example: nums = [7, 7, 7, 7, 7] nums[2] = 5 print(nums)Try It Yourself Result:>>> [7, 7, 5, 7, 7] >>> List Operations Lists can be added and multiplied in the same way as strings. For example: nums = [1, 2, 3] print(nums + [4, 5, 6]) print(nums * 3)Try It Yourself Result:>>> [1, 2, 3, 4, 5, 6] [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> Lists and strings are similar in many ways - strings can be thought of as lists of characters that can't be changed. List Operations To check if an item is in a list, the in operator can be used. It returns True if the item occurs one or more times in the list, and False if it doesn't. words = ["spam", "egg", "spam", "sausage"] print("spam" in words) print("egg" in words) print("tomato" in words)Try It Yourself Result:>>> True True False >>> The in operator is also used to determine whether or not a string is a substring of another string. List Operations To check if an item is not in a list, you can use the not operator in one of the following ways: nums = [1, 2, 3] print(not 4 in nums) print(4 not in nums) print(not 3 in nums) print(3 not in nums)Try It Yourself Result:>>> True True False False >>>

Strings multiplied

Strings can also be multiplied by integers. This produces a repeated version of the original string. The order of the string and the integer doesn't matter, but the string usually comes first. Strings can't be multiplied by other strings. Strings also can't be multiplied by floats, even if the floats are whole numbers. >>> print("spam" * 3) spamspamspam >>> 4 * '2' '2222' >>> '17' * '87' TypeError: can't multiply sequence by non-int of type 'str' >>> 'pythonisfun' * 7.0 TypeError: can't multiply sequence by non-int of type 'float'

Tuples

Tuples Tuples are very similar to lists, except that they are immutable (they cannot be changed). Also, they are created using parentheses, rather than square brackets. Example:words = ("spam", "eggs", "sausages",) You can access the values in the tuple with their index, just as you did with lists: print(words[0])Try It Yourself Trying to reassign a value in a tuple causes a TypeError. words[1] = "cheese" Tuples Tuples can be created without the parentheses, by just separating the values with commas. Example: my_tuple = "one", "two", "three" print(my_tuple[0])Try It Yourself Result:>>> one >>> An empty tuple is created using an empty parenthesis pair.tpl = () Tuples are faster than lists, but they cannot be changed.

Type Conversion

Type Conversion In Python, it's impossible to complete certain operations due to the types involved. For instance, you can't add two strings containing the numbers 2 and 3 together to produce the integer 5, as the operation will be performed on strings, making the result '23'. The solution to this is type conversion. In that example, you would use the int function. >>> "2" + "3" '23' >>> int("2") + int("3") 5Try It Yourself In Python, the types we have used so far have been integers, floats, and strings. The functions used to convert to these are int, float and str, respectively. Type Conversion Another example of type conversion is turning user input (which is a string) to numbers (integers or floats), to allow for the performance of calculations. >>> float(input("Enter a number: ")) + float(input("Enter another number: ")) Enter a number: 40 Enter another number: 2 42.0


Kaugnay na mga set ng pag-aaral

Biology Chapter 4 Study Test Questions

View Set