This question already has answers here:
Quickly append value to a list [closed]
(4 answers)
Closed 4 years ago.
I've been following a tutorial exactly but my list isn't appending--I get the error, "AttributeError: 'list' object attribute 'append' is read-only."
My code is:
mylist = [1,2,3]
mylist.append = (4)
Thank you in advance.
mylist = [1,2,3]
mylist.append = (4) # Wrong!!
append is a method that is used to add an element to an existing list object. If the object contains 3 elements and you wish to append a new element to it, you can do it as follows:
mylist.append(4)
There is something very important to note here. Whenever you do something like this:
mylist = [] # or mylist = list()
You are creating an object of type list. Hence, if you are familiar with OOP concepts, append is a member function of the class. To further verify this, you can do something like this: (Using Python 3.7)
>>> a = []
>>> type(a)
<class 'list'>
Welcome to programming!
Append is a (read-only) function. You don't assign to it, you call it.
mylist.append(4)
is what you're looking for!
append is a function so use mylist.append(4) and it should work fine.
append is an attribute of List. If you want to append an item to your list use append as a function.
mylist = [1, 2, 3]
mylist.append(4)
print(mylist)
>> [1, 2, 3, 4]
what you are currently doing it you are trying to override the append function to be = 4
append is function it takes the argument which you want to append:
e.g.
.append()
Related
This question already has an answer here:
Why a generator object is obtained instead of a list
(1 answer)
Closed 3 years ago.
Not sure if this has been asked before but I couldn't find a proper, clear explanation.
I had a concern about something related to python syntax.
While practicing some python, I Intuitively assumed this would print all the elements of the list; list1.
But it doesn't seem to do so, why would that be?
I could obviously print it in many other ways; but I fail to understand the inherent python logic at play here.
list1 = [1,2,3,4]
print(list1[i] for i in range(len(list1)))
I expected the output to be '[1, 2, 3, 4]', but it instead prints a generator object.
You need to surround list1[i] for i in range(len(list)) with [] to indicate that it's a list. Although list1 is a list, you are trying to use a generator expression to print it out, which will return a generator object (type of iterable similar to a list.) Without specifying you want to convert the generator to a list, it won't print a list. (A generator expression converted to a list is called list comprehension.)
Even if you did do this, it would still print it [1, 2, 3, 4] rather than 1 2 3 4. You need to do [print(list1[i], end=" ") for i in range(len(list1)))] for that to work. There are far better ways of doing this: see donkopotamus's answer.
The expression (list1[i] for i in range(len(list))) defines a generator object. So that is what is printed.
If you wish to print a list, then make it a list comprehension rather than a generator, and print that:
print( [list1[i] for i in range(len(list1))] )
Alternatively, you could force evaluation of the generator into a tuple (or list or set), by passing the generator to the appropriate type using eg
print(tuple(list1[i] for i in range(len(list1))))
In order to get the specific output you intended (space separated) of 1 2 3 4 you could use str.join in the following way:
>>> list1 = [1, 2, 3, 4]
>>> print(" ".join(list1[i] for i in range(len(list1))))
1 2 3 4
or unpack the list into print (this will not work in python 2, as in python 2 print is not a function)
>>> print(*(list1[i] for i in range(len(list1))))
1 2 3 4
(list1[i] for i in range(len(list1)))
is indeed a generator object, equivalent to simply
(x for x in list1)
You're passing that generator to print as a single argument, so print simply prints it: it does not extract the elements from it.
Alternatively, you can unpack it as you pass it to print:
print(*(list1[i] for i in range(len(list1))))
This will pass each element of the generated sequence to print as a separate argument, so they should each get printed.
If you simply meant to print your list, any of the following would have worked:
print(list1)
print([list1[i] for i in range(len(list1))])
print([x for x in list1])
The use of square brackets makes a list comprehension rather than a generator expression.
There is something called list comprehension and generator expression in python. They are awesome tools, you can find more info by googling. Here is a link.
Basically, you can make a list on the fly in python.
list1 = [1,2,3,4]
squared_list = [i*i for i in list1]
would return a list with all the items squared. However, is we say
squared_gen_list = (i*i for i in list1)
this returns what is known as a generator object. That is what is happening in your case, as you can see from the syntax and so you are just printing that out. Hope that clears up the confusion.
This question already has answers here:
The zip() function in Python 3
(2 answers)
Closed last month.
Created two lists in python and zipped them using zip function and saved them to a variable. Tried to print it to the console and was able to print successfully and when i tried again,empty list is printed.screenshot
Same with tuples.screenshot
Why i am able to retrieve values only once? Am in doing something wrong?
Python 3.7.1
The zip function is actually just an iterator -- an iterator can only be traversed once. If you want to be able to iterate over it multiple times, convert it to a list first.
a = [1,2,3]
b = [1,2,3]
c = list(zip(a, b))
Why is this?
Because those are similar to generators, so you can print first time, but when you try to print it again, it starts from the end, and no values left, see an example (clearer than yours):
>>> l=[1,2,3,4]
>>> it=iter(l) # generator basically (as in your question, zip, is also considered as a geneartor here)
>>> list(it)
[1, 2, 3, 4]
>>> list(it)
[]
>>>
So how to solve this issue?
Simply just replace this line:
zipped_list = zip(list1,list2)
With:
zipped_list = list(zip(list1,list2))
Then everything would work fine.
This question already has answers here:
Ellipsis lists [...] and concatenating a list to itself [duplicate]
(3 answers)
Closed 6 years ago.
I have a list X = ['xyz']
I use the below commands for appending to another variable.
L = X
L.append(X)
L
Out[109]: ['xyz', [...]]
I am unable to understand why the second element in the new L list is not having the value as 'xyz'
My question is not how to append or extend a list, but in fact about the functionality of Append function, which has been correctly explained by #sinsuren below.
append add X as an element to L. If you want the element inside X to be inserted to L, use extend instead:
>>> X = ['xyz']
>>> L = X
>>> L.extend(X)
>>> L
['xyz', 'xyz']
Try this, it will extend the list.
L.extend(X)
But if you want to use append. Use a element like this L.append('abc'). It will give same result or L.append(X[0])
Edit: You have Appended list to itself. It will recursively append to itself and due to which even L[1] will give you same response. Like L[1] = ['xyz', [...]] . and for more understanding Please refer What's exactly happening in infinite nested lists?
Sometimes I have a list and I want to do some set actions with it. What I do is to write things like:
>>> mylist = [1,2,3]
>>> myset = set(mylist)
{1, 2, 3}
Today I discovered that from Python 2.7 you can also define a set by directly saying {1,2,3}, and it appears to be an equivalent way to define it.
Then, I wondered if I can use this syntax to create a set from a given list.
{list} fails because it tries to create a set with just one element, the list. And lists are unhashable.
>>> mylist = [1,2,3]
>>> {mylist}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
So, I wonder: is there any way to create a set out of a list using the {} syntax instead of set()?
Basically they are not equivalent (expression vs function). The main purpose of adding {} to python was because of set comprehension (like list comprehension) which you can also create a set using it by passing some hashable objects.
So if you want to create a set using {} from an iterable you can use a set comprehension like following:
{item for item in iterable}
Also note that empty braces represent a dictionary in python not a set. So if you want to just create an empty set the proper way is using set() function.
I asked a related question recently: Python Set: why is my_set = {*my_list} invalid?. My question contains your answer if you are using Python 3.5
>>> my_list = [1,2,3,4,5]
>>> my_set = {*my_list}
>>> my_set
{1, 2, 3, 4, 5}
It won't work on Python 2 (that was my question)
You can use
>>> ls = [1,2,3]
>>> {i for i in ls}
{1,2,3}
I'm having trouble figuring out how to remove something from within a nested list.
For example, how would I remove 'x' from the below list?
lst = [['x',6,5,4],[4,5,6]]
I tried del lst[0][0], but I get the following result:
TypeError: 'str' object doesn't support item deletion.
I also tried a for loop, but got the same error:
for char in lst:
del char[0]
Use the pop(i) function on the nested list. For example:
lst = [['x',6,5,4],[4,5,6]]
lst[0].pop(0)
print lst #should print [[6, 5, 4], [4, 5, 6]]
Done.
Your code works fine. Are you sure lst is defined as [['x',6,5,4],[4,5,6]]? Because if it is, del lst[0][0] effectively deletes 'x'.
Perhaps you have defined lst as ['x',6,5,4], in which case, you will indeed get the error you are mentioning.
You can also use "pop". E.g.,
list = [['x',6,5,4],[4,5,6]]
list[0].pop(0)
will result in
list = [[6,5,4],[4,5,6]]
See this thread for more: How to remove an element from a list by index in Python?