138 views

3 Answers

1 1 vote

Initially:

L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]

The loop starts with $\texttt{e = 1}$. Since $1$ is present in $\texttt{L2}$, it is removed from $\texttt{L1}$.

L1 = [2, 3, 4]

Now the important point is that the list is being changed while the loop is running. Python's loop moves to the next index, so it skips $2$.

Therefore, $2$ is not removed.

Final output:

[2, 3, 4]
0 0 votes
This can be a reason of skipping the element :-

In python everthing is a object and every variable refernce some object

so now,

let say we have a list L

if we remove the list in which we are traversing so because of the referancing we unkowingly vhange the size of the list so it feels like we skip the element but internally it happens becasuse we changed the no of element in the list which cause the skipping

Ex-  

L=[1,2,2,3,4]

we are traversing on the list and let say we want to remove the element 2

index = 0

it compares the list L[0] = 1

nothing happens

list is L=[1,2,2,3,4] [becsue we have the referance of the list]

goes to next index

 

index = 1

it compares list L[1] = 2

removes the element

now the list is L=[1,2,3,4]

goes to next index

 

index = 2

L=[1,2,3,4]

in this list L[2] = 3

goes to next index

 

index = 3

L=[1,2,3,4]

index 3 L[3] = 4

nothing happens

goes to next index

 

condition false "terminate the loop"

 

Correct me if i am wrong in here

thank you 😄
Answer:
Position:
Show:

Related questions

1 1 vote
2 2 answers
142
142 views
GO Classes asked Jul 3
142 views
A grid contains '$\texttt{s}$' for sand, '$\texttt{r}$' for rock, and $\texttt{None}$ for empty.The operation $\texttt{jumpdown(grid, x, n)}$ works on one column $\texttt...
1 1 vote
2 2 answers
118
118 views
GO Classes asked Jul 3
118 views
Suppose $\texttt{zeroArray(3, 4)}$ creates a $2$D array with $3$ rows and $4$ columns, filled with zeros.Now consider:v = zeroArray(3, 4)Which expression correctly change...
2 2 votes
2 2 answers
123
123 views
GO Classes asked Jul 3
123 views
Consider the following Python code:def group_by(s, fn): grouped = {} for x in s: key = fn(x) if key in grouped: grouped[key].append(x) else: grouped[key] = [x] return gro...
2 2 votes
2 2 answers
126
126 views
GO Classes asked Jul 3
126 views
Consider the following Python code:def insert_items(s, before, after): index = 0 while index < len(s): if s[index] == before: s.insert(index + 1, after) index += 1 index ...