Creating a linked list

Hi, I need help creating a linked list by popping numbers off a list.
I have to use a loop, cannot assign variables one by one

 class ListNode:
         def __init__(self, x):
         self.val = x
         self.next = None

#Lets say we have a list

List1 = [1,2,3,4]

# We want to turn it into a linked list, here is my attempt

answer = ListNode(list1.pop(0))
while list1:
       answer = answer.next
       answer = ListNode(list1.pop(0))
return answer

This doesnt work. I just reassigns the original link in the list.

Do I have to create a recurring function?

Maybe you should do it without the loop so that you can at least figure out the right actions. For example, you would need to modify the next attribute, that’s the link. Then look at what you write and put the repeated thing in a loop.
Having a loop doesn’t change what you do.
Or do it with pen and paper. What is the repeated action? Put that in a loop. When you do it with pen and paper you will be manipulating things that you have to represent in your code as well, it’s a 1:1 correspondence, that’s your reference to what to do.

Use prints to write out your representation at each step if that helps you. Obviously, you’d need to write code for representing it as text first. Use pen and papper as reference, pick the first thing, write the code, check the output… then pick the next thing that you want to make happen, write out the result again, and so on.

For example. Your variable answer. What should that be referencing by the end? Pen and paper, what is the result?
What would you do with that information using pen and paper?
You’d probably never change what it refers to. But in your code… That’s not a code mistake, that’s got to do with deciding what basic actions should happen.


Your answer variable.
answer.
The final result.
answer is the list then, yes?
What is a list?
A list is either empty, or it is a node, and from that node you can follow the link to the rest, and so on, all they way to the end.
So what would answer refer to? It’s the first node of the list. After you’ve set it to the first node at the very start, you would therefore never change it.

1  ->  2  ->  3  ->  4
^
answer

You’re doing this instead:

1      2      3      4
                     ^
                     answer

For traversing a list with pen and paper, you would point at the start. Your finger is the reference.
You would look at where that node points, move your finger there.
You would look at where that node points, move your finger there.
You would look at where that node points, move your finger there.
You would look at where that node points, move your finger there.
You would look at where that node points, move your finger there.
Note that this only mentions the node the finger points at, and the one after it.
It never does anything resembling here.next.next.next.next. It never involves “three steps ahead of the finger” because you move the finger during each iteration.

Once reaching the end, you could take a pen and draw an arrow from the last node to a new one. You have a reference to the last node, your finger. And you know that you need to modify its next attribute by drawing an arrow. You could then move your finger to the new end, and draw another arrow, and so on.

This is somebody elses code

        l1 = [1,2,3]
        l2 = [4,5,6]
#l1 and l2 are linked lists
        l3 = None
        a = 0
        while l1 or l2 or a:
            if l1:
                a += l1.val
                l1 = l1.next
                
            if l2:
                a += l2.val
                l2 = l2.next
                
            if l3:
                l3.next = ListNode(a%10)
                l3 = l3.next
            else:
                l0 =  ListNode(a%10)
                l3 = l0

            a = a//10

        return l0```

In this example l0 is returned even though it was only modified it once. How did l3 affect the outcome of l0? This is a working solution by the way. l3 was the main link being built and in the end somehow I0 can be returned?

What do you mean by modifying it once? It’s all the same list isn’t it? So it’s being modified plenty.
And why should it be reassigned? If you create a list, then you’ve got the list, there’s no reason to suddenly refer to something else, the list that was created is the result. This is the same for a python list:

x = []
x.append(3)
x.append(3)
x.append(3)

Which I’ve also suggested before.
Create a list and append to it, then return the list.

And if you draw a linked list, then the first node you create remains the first node. You don’t replace it, so therefore you wouldn’t replace it in code either since that is doing the same thing.

you could write l0 on paper, point it at a node, point l3 at the same node, because it says so in the code … then append at l3, move l3, and so on. everything you do in code you do on paper and the other way around, which is why you can use paper as a reference.

I0 and I3 are two different linked lists right? I3 is on the left side of the assignment operator, not I0 so how can I0 be affected by the modifications of I3. The first node of I0 was assigned and the last node was assigned to it, everything else in between was assigned to I3. Then I0 is returned in the end. I’ll try to paper and pencil this one, but I think the result will be the same

I just papered and penciled it, following the steps. He only modifies I0 two times, replacing the original 5 he set to it with 0 a the end

Or how do else statements work with 3 if statements? Is it triggered it only one of the if conditions are not met?

I just found out it doesnt work 100% Oof

How are you measuring that?

x = ListNode(1, ListNode(5, ListNode(3)))
y = ListNode(4, ListNode(5, ListNode(6)))
print(show(addtwo(x, y)))
[5, 0, 0, 1]

yes and no. yes because of characteristics of linked list, but no, because they both refer to the same structure. whenever you see assignment, draw an arrow from that variable to that node. If you drew what’s said in that code you’re not going to end up with two lists, the nodes are linked, that’s what the structure of a linked list is, isn’t it…

Like I said, if you append to a list then you can view the appended values from your reference to the list. You can observe this with pen and paper, if you make a node, give it a value, and point at it, then append a bunch of stuff, then the thing you’re pointing at will now be a longer list than it originally was. This is also how a python list behaves.

x is only assigned once, that doesn’t mean it’s empty after this code has run.

He said his code doesnt pass all of the tests. but anyways, I just wanted to take a list of length n and transform it into a linked list. I cant use a while loop and pop off each element because it doesn’t work by itself. I feel like I understand the pen and paper. I just dont know how to organize it with code

If you use a while loop, you can cycle through a linked list but u cannot create one by itself. I probably have to use recursion which I hate

It’d be cool if you could map a list into a linked list

map fundamentally does not convert type, map is structure-preserving.
The thing you say you want to do is exactly what map does not do.
You can reduce from python list to linked list, but the combining action is append.
map and reduce are just loops, they don’t give you new abilities.

you probably shouldn’t be using python lists for anything in that problem, you shouldn’t need a list to implement a list

a while-loop can create a list just fine, since it is a loop and if you do append in a loop then you will build a list… the code you posted is appending, and it is a while-loop

My suggestion is still very much to do it on paper.

Draw two input lists.
Carry out the task. Observe yourself.

No, code is not different. Your problem isn’t organizing it in code, the code is trivial. What you need is to figure out what you’re doing, without having decided what actions to carry out there’s no way you’re accidentally going to get it right.

You’ve got a very small very trivial set of operations.
set next
read next
set val
read val
create empty
create node
compare to empty

loop lets you do those things repeatedly. it does not in any way change what you do, it is those same operations. you would simply identify what of those operations you’re repeating, and put that in the loop.

as such, all that remains is deciding what to do. pen and paper. use the operations above. observe what you do. identify where the repeated action begins and ends.

Why would I need to set val? I only need it to set a node

ans = ListNode(l1.val)

can and need aren’t the same thing
…but arguably you are setting it or it’d have no value

And in terms of those operations, you can create a list:

in order to create a list of: 1 2 3 4 5
do:
           mylist = create node
           set mylist's val to 1
           mytail = mylist
this is  | set mytail's next to (create node)
a loop   | set mytail to mytail's next
         | set mytail's value to 2
        |  set mytail's next to (create node)
        |  set mytail to mytail's next
        |  set mytail's value to 3
         | set mytail's next to (create node)
         | set mytail to mytail's next
         | set mytail's value to 4
        |  set mytail's next to (create node)
        |  set mytail to mytail's next
        |  set mytail's value to 5
           result is mylist

And if you write the operations down, you can identify that something repeats. You would put this in a loop.

So, you can observe what you do with paper to obtain instructions as above. You can identify a loop by finding what repeats. All the operations used are trivial things corresponding directly to code, nothing needs to change for it to be translated to code.

I cant get it right for some reason. I’ve tried everything except the right answer.

I’ve tried this for this problem, same concept: https://leetcode.com/problems/merge-two-sorted-lists/

def addTwoNumbers(self, l1: ListNode, l2: ListNode, count = 0) -> ListNode:
        current = l1
        current2 = l2
        stack = [l1.val, l2.val]
        while current.next != None:
            current = current.next
            stack.append(current.val)
        while current2.next != None:
            current2 = current2.next
            stack.append(current2.val)
        stack.sort()
        val = ListNode(stack[count])
        while count <= 5:
            val.next = self.mergeTwoLists(l1, l2, count)
        return val

But the problem is I get an "near infinite’ loop

Read my reply which shows how pen and paper relates to code.
You should be able to write down instructions like that based on observing what you do with paper.
You should be able to write that down as code since it uses those basic instructions each of which corresponds to simple code.

don’t use a different list, don’t use python’s builtin list.
you’re implementing a list operation
you should not need another list to do it
use the list you already have

wont that be easier tho? I have to sort each list so they’re in order. Then make the final linked list from the list

Based on that I only really need help with everything after stack.sort() unless you think otherwise