append function in python [duplicate] - python

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?

Related

Remove or pop is not eliminating all the elements [duplicate]

This question already has answers here:
Why does Python skip elements when I modify a list while iterating over it?
(8 answers)
Closed 2 years ago.
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(lis)
Output:
[3,4]
I tried pop() also but couldn't remove all elements
The reason why you are not able to remove all the elements is that when you are removing an element from the array the j value skips to the next value's next value instead of the next. So only the alternative values will be removed by this method.
lis = [3,4,5,6]
for j in lis:
lis.remove(j)
print(j)
print(lis)
Output
3
5
[4,6]
As you can see in this output print(j) does not print all the elements, it only prints 3 and 5. So only 3 and 5 are removed.
How to solve it?
So you can either use clear(), like this
lis.clear()
Or if you want to use iteration you can do it with pop() like this
for i in range(len(lis)):
lis.pop(i)
Or you can create a shallow copy of the list and remove() the elements one by one like this
for i in list(lis):
lis.remove(i)
Or you can use : to return the whole slice of the array (copy of the array)
for i in x[:]:
x.remove(i)
use clear to clear all the element of the list
lis =[3,4,5,6]
lis.clear()
print(lis)
Output:
[]
A correct solution will be to create a shallow copy with the help of list() function.
lis =[3,4,5,6]
for j in list(lis):
lis.remove(j)
print(lis)
Output
[]

Why my code is not able to convert each item of list from string to integer? [duplicate]

This question already has answers here:
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 3 years ago.
I am stuck on a problem due to a small portion of my code. I can't find why that portion of code is not working properly.
By debugging each portion of my code, I found which lines are causing unexpected results. I have written that lines below. I have defined the list here so that I do not have to copy my full code.
list1=["-7","-7","-6"]
for test in list1:
test=int(test)
print( type( list1[0] ) )
I expected type to be int but output is coming as str instead.
You need to modify the content of the list:
list1=["-7","-7","-6"]
for i in range(len(list1)):
list1[i] = int(list1[i])
print(type(list1[0]))
A more pythonic approach would be to use a comprehension to change it all at once:
list1 = [int(x) for x in list1]
Try this to convert each item of a list to integer format :
list1=["-7","-7","-6"]
list1 = list(map(int, list1))
list1 becomes [-7, -7, -6].
Now type(list1[0]) would be <class 'int'>
You forgot about appending the transformed value:
list1 = ["-7","-7","-6"]
list2 = [] # store integers
for test in list1:
test = int(test)
list2.append(test) # store transformed values
print(type(list2[0]))

Python list not appending [duplicate]

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()

How can I remove multiple elements from a list? [duplicate]

This question already has answers here:
Different ways of clearing lists
(8 answers)
Closed 4 years ago.
list1 = [2,5,61,7,10]
list1.remove(list1[0:len(list1)-1])
print(list1)
I want to remove all elements from that list but it shows me syntax error.
Any idea how can I remove all elements and print the final result like []
To remove all list items just use the in-built .clear() function:
>>> list1 = [2,5,61,7,10]
>>> list1.clear()
>>> print(list1)
[]
>>>
If you want to remove all elements from a list, you can use the slice assignment:
list1[:] = []
But with list.remove(), you can only do it one-by-one:
for item in list(list1):
list1.remove(item)
Note I created a copy of list1 with the for loop because it's dangerous to modify what you're iterating over, while it's safe to modify the list while iterating over a copy of it.
To remove some of the items:
for item in list1[0:3]:
list1.remove(item)
Or just better yet, use slice assignment:
list1[0:3] = []

Delete list elements after using them [duplicate]

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 7 years ago.
I have a list
test_list = [1,2,3,4,5]
I want to iterate over the elements of this list and delete them after using. But when I try to do this
for element in test_list:
print element
test_list.remove(element)
Alternate elements are printed and removed from test_list
1
3
5
print test_list
[2, 4]
Please explain why this happens!
Read the answers to strange result when removing item from a list to understand why this is happening.
If you really need to modify your list while iterating do this:
>>> items = ['x', 'y', 'z']
>>> while items:
... item = items.pop()
... print item
...
z
y
x
>>> items
[]
Note that this will iterate in reverse order.
in python this concept is called an iterator
my_iter = iter(my_list)
each time you consume or look at an element it becomes gone ...

Categories

Resources