Question: Python - how to create a function that creates a list counting tuples. I am not fully understanding the tuples part here because it has
Python - how to create a function that creates a list "counting" tuples. I am not fully understanding the tuples part here because it has random first and last name. I have created the required SQLite database, but I get stuck on how to populate it with people that have random names. Basically I get stuck on the tuples part, please advise.
def generate_people(count):
- This function will create a list of count tuples (ID, First Name, Last Name), each of which has a random first and last name.
- Note: The ID should simply be the counter you use in your loop/comprehension.
- Create two lists, last_names and first_names and initialize them to [].
- Using a file context manager, open the LastNames.txt file for read-only access:
with open('LastNames.txt', 'r') as filehandle:
- Inside the with context block, loop through the file using the filehandles readline() function and place each name read into last_names.
- A better approach would be to use a comprehension using filehandless readlines() function.
- If you are noticing weird characters at the end of each name (carriage returns or line feeds), dont forget about Strings rstrip() function.
- Once you have the last_names list populated, perform a similar process for the first_names list.
- Now that both name lists are loaded you must create the tuple list of random names.
- Create a for loop (or better yet, a comprehension) that creates count tuples ina list called names, where:
- The first item of the tuple is the ID of the person use the counter variable of the for loop
- The second item is the first name. Use random.randint() to determine a name to pull out of first_names. Dont forget to use the len() function on first_names when getting a random index from randint.
- The third item is the last name. Pretty much the same process as the first name item above.
- Dont forget you create a tuple with the following syntax:
my_tuple = (item1, item2, item3)
- Now, create a main block at the bottom pf Lab5.py and test the generate_people() function:
if __name__ == "__main__":
people = generate_people(5)
print(people)
- Sample output:
[(0, 'JONATHAN', 'VILLARREAL'), (1, 'HARRIETTE', 'MAY'), (2, 'GALE', 'SAVAGE'), (3,
'MALISSA', 'BRANDT'), (4, 'MERCY', 'RAY')]
- Note: If the output is missing the parentheses around each person, then you did not create tuples. If there is an extra set of square brackets around each person then that is a list of lists, not a list of tuples.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
