PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

[FIXED] Why is the Output of these Two Lists Different?

 September 15, 2022     append, list, printing, python     No comments   

Issue

import random

words = ['nugget', 'jasmine', 'trolley', 'weight', 'soap']
mywords = []

random.shuffle(words)
mywords.append(random.sample(words, 2))

print("Words: ")
for i in words:
    print(str(i))

print("My Words: ")
for i in mywords:
    print(str(i))

I am working on an example that moves items from one list to another. The example seems to work as intended except for the output of the second list 'mywords', which prints in brackets and not as an unordered list as the list 'words' prints. Any suggestions? My guess is it has something to do with the append function I used.


Solution

The function random.sample() returns a list. The function list.append() takes the item you pass as an arugment, in this case a list, and adds it to the end of your list. If you replace append() with extend() it will add each item returned from random.sample() to the list individually.



Answered By - Nathan Roberts
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing