0

I'm trying to add two lists f and l as shown below. f and l don't have the same shape so I made the shape of f similar to l

f = [37.37, 34.26, 33.78, 33.82, 36.33]

f.append(f)

l = [[34.4 , 39.32, 35.61, 38.12, 34.11], 
     [33.1 , 35.14, 36.76, 33.66, 34.31]]
z = f + l

but I'm getting this strange output :

[37.37, 34.26, 33.78, 33.82, 36.33,
 [37.37, 34.26, 33.78, 33.82, 36.33, [...]],
 [34.4, 39.32, 35.61, 38.12, 34.11],
 [33.1, 35.14, 36.76, 33.66, 34.31]]

I wasn't expecting [...], so I checked the value of f and it was

[37.37, 34.26, 33.78, 33.82, 36.33, [...]]

different from before,

can someone explain to me what is happening here I'm quite new to python.

blaze
  • 59
  • 6
  • 1
    Short answer: use `extend` instead of `append`. You use `append` to add a single element to a list. If that element is a list, you end up with a nested list, which is what the `[...]` in your output represents. – Samwise Feb 12 '21 at 16:40
  • You can also use `f *= 2` if you just want to double the list -- that's a little more idiomatic than `f.extend(f)` IMO. – Samwise Feb 12 '21 at 16:41
  • @Samwise I'm a bit confused, what's the value of [...] – blaze Feb 12 '21 at 16:48
  • `[...]` is just a way to shorten the list when printed. – Nerveless_child Feb 12 '21 at 17:32
  • Those ellipses are used when you have a list that references itself, otherwise the naive representation would be infinitely recursive – juanpa.arrivillaga Feb 12 '21 at 18:26

1 Answers1

2

You should try f = [f, f] instead of f.append(f).

You are trying to append a list at the last position of your list, resulting in your nested list (the [...] is the abbreviated version of f, used by the print function).

Stijn De Pauw
  • 332
  • 2
  • 9