Append function

Hi, I’m new to programming, so these might be basic questions.
I want to understand the actual role of the append function. Does it just “add”-(not the mathematical addition?) but just adds someting to the list?
Also, when you use append in the loop, does it always have to be apended to a list already declared as empty?
Can you append a string to a float or integer, and viceversa? Can you append two or more lists with different types together? How would you perform mathematical functions on appended lists?

Hey rachaelchris517,

I’m a relatively new user, new to programming, so we’re in this together! I will try to help as best possible. The append function does not add in a mathematical sense, but instead inserts an item into an empty or existing list (at the end of the list) to extend the length of the list.

Regarding appending in a for loop, the list does not always have to be empty that you’re appending into. In fact when you run the for loop, it is no longer empty after a certain number of iterations in most cases. Sometimes you will need to use logic to check if an item is already in a list (using an if in statement) and choose to append the item to the list or not to append it. But that depends on whether you want duplicates of a value in your list. Here’s an example I pulled from stack overflow:

 list_i_have = [1, 2, 4]  
 list_to_compare = [2, 4, 6, 7]

 for l in list_i_have:
     if l not in list_to_compare:
         do_something()
     else:
         do_another_thing()

Regarding the dtypes of the list items, you can use any dtype combination within the list you’re appending (for example you can add an integer to a list of strings, or a string to list of integers, etc.)

If you are looking to combine lists that are already defined/contain their values, you wouldn’t use the append function but would instead use a mathematical operator to concatenate the two lists bringing them together (see more info on this from stack overflow)

Using + operator to combine lists
A_list = [1, 2, 3, 4]
B_list = [5, 6, 7, 8]
Combined = A_list + B_list
Output
>>> Combined
[1, 2, 3, 4, 5, 6, 7, 8]

For reference, this site has a good explanation of the append function!

I might not know exactly what you’re talking about in terms of applying a mathematical operation to lists in python, but there a few different ways to change values in a list (for example multiplying all values in the list by two). This is assuming the list contains all integers or float dtypes. Here’s a link to a stack overflow discussion on doing math to a list, with examples.

I hope this helps and maybe some others will chime in with their thoughts. Good luck in your journey!!

2 Likes

thanks @mkurylowski . I appreciate the detailed explanations and examples you provided. Good luck in your journey too! We got this!!!

1 Like