简体   繁体   中英

Appending to list of lists

I'm a real newbie with Python and struggling with the lack of arrays. I could use numpy of course but it feels like a cop out for someone trying to learn. So with that said why can't I use append with a list of lists? Here is my code

myList = ['Tom','Colin']

# so now my list is ['Tom', 'Colin']
myList.append('Tom')

# Append works so now my list is ['Tom', 'Colin', 'Tom'] Yes I did mean to have two Tom entries

myListOfLists=['Tom', '24'],['Colin', '25']
row =  ['Tom', '31']

myListOfLists.append(row)
# this gives the dreaded AttributeError: 'tuple' object has no attribute 'append' error

I don't understand why I can't append to a list of lists

myListOfLists is not a list of lists. It is a tuple of lists.

Replace

myListOfLists=['Tom', '24'],['Colin', '25']

With

myListOfLists=[['Tom', '24'],['Colin', '25']]

tuple do not have any append method, but list have.

myListOfLists=['Tom', '24'],['Colin', '25']
print(type(myListOfLists))
# <class 'tuple'>
print(hasattr(myListOfLists, 'append'))
# False

myListOfLists=[['Tom', '24'],['Colin', '25']]
print(type(myListOfLists))
# <class 'list'>
print(hasattr(myListOfLists, 'append'))
# True

When you write

myListOfLists=['Tom', '24'],['Colin', '25']

you do not create a list of list, but a pair (tuple of 2 elements) containing two lists of two elements each.

A tuple cannot be modified (we say they are immutable), that's why calling append on a tuple raises an error.

If you want a list of list, you want to write

myListOfLists=[['Tom', '24'],['Colin', '25']]

and your code will work.

you can't use list.append because myListOfLists is a tuple


you can have a new list where you unpack the previous values of myListOfLists and include also your row :

myListOfLists=['Tom', '24'],['Colin', '25']
row =  ['Tom', '31']

myListOfLists = [*myListOfLists, row]

# [['Tom', '24'], ['Colin', '25'], ['Tom', '31']]

You have to encase myListOfLists in brackets [] :

myListofLists = [['Tom', '24'],['Colin', '25']]
myListofLists.append(['Tom', '31'])
print(myListofLists)
# returns [['Tom', '24'], ['Colin', '25'], ['Tom', '31']]

See, so now you have a list of lists!

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