0

Beginner here but I have an important question.

s1 = [1,2,3,4,5]
s2 = [6,7,8,9,0]

for x in s1:
    y = [len(s2), x]

y

Take this code for example. It returns [5,5]. However, in the background, it loops through [5,1], [5,2], etc. until it reaches [5,5].

Question: How do I make it return
[[5,1],[5,2],[5,3],[5,4],[5,5]] exactly like that??

  • 1
    Possible duplicate of [What does "list comprehension" mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – mkrieger1 Sep 23 '17 at 17:43

4 Answers4

1

You can make y an empty array and each time append to it using append:

s1 = [1,2,3,4,5]
s2 = [6,7,8,9,0]
y = []
for x in s1:
    y.append([len(s2), x])

print(y) # => [[5, 1], [5, 2], [5, 3], [5, 4], [5, 5]]

You can also lose some lines using a list comprehension:

y = [[len(s2), x] for x in s1]
print(y) # => [[5, 1], [5, 2], [5, 3], [5, 4], [5, 5]]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
1

Your code reassigns a new value to y on each iteration without saving it anywhere, so when you finally want to check it, it only displays the value which was assigned to it on last iteration. Instead, you need to save (append) the value to a new list. The most elegant solution would be to use a simple list comprehension:

>>> s1 = [1, 2, 3, 4, 5]
>>> s2 = [6, 7, 8, 9, 0]
>>> y = [[len(s2), x] for x in s1]
>>> y
[[5, 1], [5, 2], [5, 3], [5, 4], [5, 5]]

...which is equivalent to:

y = []

for x in s1:
    y.append([len(s2), x])

... or ...

y = []

for x in s1:
    y += [[len(s2), x]]
adder
  • 3,512
  • 1
  • 16
  • 28
0

Like this:

s1 = [1,2,3,4,5]
s2 = [6,7,8,9,0]
s3=[]
for x in s1:
    y = [len(s2), x]
    s3.append(y)
y=s3
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
-1

Have the Y inside the loop so it get's printed in everyloop.

for x in s1:
    y = [len(s2), x]
    print y,
Darshan Jadav
  • 374
  • 1
  • 3
  • 15