Python Forum
Why the this extend example is printing 2 two times?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why the this extend example is printing 2 two times?
#1
Why the this extend example is printing 2 two times?

def my_fun(x):
    for k in range (len(x)):
        print('k is ',k)
        x.extend(x[:k])
        print('x is',x)
m = [2,4,3]
my_fun(m)
print(m)
Out Put

k is 0
x is [2, 4, 3] 0th element is 2 but it does not insert that here.
k is 1
x is [2, 4, 3, 2]
k is 2
x is [2, 4, 3, 2, 2, 4] After 3 why 2 is being inserted two times
[2, 4, 3, 2, 2, 4]
Reply
#2
The list x is extended by its ks first elements for k in 1, 2, 3, …. Thus x is extended by [], then by [2], then by [2, 4]. That's why 2 is appended twice.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  View and extend native python class PythonDev 2 1,643 Oct-24-2020, 08:59 PM
Last Post: Gribouillis
  How to extend the sclale of a graph? Krszt 1 2,313 Nov-13-2018, 11:16 AM
Last Post: Larz60+
  Extend the scale Krszt 1 2,687 Nov-05-2018, 01:16 PM
Last Post: Gribouillis
  generate filename of value and extend Marre 2 2,802 Oct-01-2018, 07:31 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020