简体   繁体   中英

How to print new list from previous list using functions in python?

def send_messages(message):
    while message:
        print(message)
        message.pop()
        sent_messages.append(message)

message = ['hello', 'i am on my way', 'cant talk right now']
sent_messages = []

send_messages(message)

print(message)
print(sent_messages)

I am learning python and having trouble trying to print 2 lists. I am trying to move values from one list to another using pop.() and append.() method However, when I run the program, it only shows me empty square brackets of the sent_messages list with no values in them.

Try this

send_messages=[]
def send_messages(message):
    while message:
        sent_messages.append(message.pop(0))

message = ['hello', 'i am on my way', 'cant talk right now']
sent_messages = []

send_messages(message)

print("message list" ,message)
print("sent_messages list", sent_messages)

Output

message list []
sent_messages list ['hello', 'i am on my way', 'cant talk right now']

you are appending to the list sent_messages only references of your list message while you are removing all the elements from your list message , in the end, you will have references to an empty list (since message list will be empty)

you could use:

message = ['hello', 'i am on my way', 'cant talk right now']

sent_messages = message.copy()
message = []


print(message)
print(sent_messages)

output:

[]
['hello', 'i am on my way', 'cant talk right now']

if you want to learn Python and use list.pop and list.append you could use:

message = ['hello', 'i am on my way', 'cant talk right now']

def send_messages(message):
    new_list = []
    while message:
        new_list.append(message.pop())  # keep in mind that .pop will pop out the last element

    return new_list[::-1] # reverse to keep message elements order

sent_messages = send_messages(message)
print(message)
print(sent_messages)

output:

[]
['hello', 'i am on my way', 'cant talk right now']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM