I want to append "," and then the item index to every item in a list of integers.
I know that I need to convert the integers to strings before I do that, but even if I do that, it isn't working:
(I use Python 3.7.3)
for element in mylist:
element = str(element)
element = "{0},".format(element)
element = element + mylist.index(element)
What I want:
mylist = ["97,0", "569,1", "39,2", "230,3",....]
Possibly someone can link to a question of which this is a duplicate, but I don't know my way around that well yet.
You want list comprehensions, and the enumerate function.
new_list = ["{0},{1}".format(item, index) for (index, item) in enumerate(old_list)]
If you absolutely positively need to change the list in-place, then you can iterate over a copy of that list and do just that.
for i, val in enumerate(mylist[:]): # note the empty slice there -- that creates a whole copy!
mylist[i] = f"{val},{i}"
Technically since you're not adding or removing elements, you are allowed to do this without that copy
for i, val in enumerate(mylist):
mylist[i] = f"{val},{i}"
but this is a dangerous habit to get into without fully understanding what you can and cannot do to a list that you're iterating over. If your goal was to do this but also remove the 10th element (or etc), you would have to make a copy. Similarly if you wanted to insert a new element before the value 97, or etc.
As general best practice, you should avoid mutating the list if possible and produce a new one using a list comprehension as recommended in ShapeOfMatter's answer
mylist = [97,0, 569,1, 39,2, 230,3]
for items in mylist:
(str(items))
print('\"{0}\"'.format(items))
Here is the solution to your question, if I understood it correctly you wanted to add for every item in the list "".
Related
I am trying to append objects to the end of a list repeatedly, like so:
list1 = []
n = 3
for i in range(0, n):
list1 = list1.append([i])
But I get an error like: AttributeError: 'NoneType' object has no attribute 'append'. Is this because list1 starts off as an empty list? How do I fix this error?
This question is specifically about how to fix the problem and append to the list correctly. In the original code, the reported error occurs when using a loop because .append returns None the first time. For why None is returned (the underlying design decision), see Why do these list operations return None, rather than the resulting list?.
If you have an IndexError from trying to assign to an index just past the end of a list - that doesn't work; you need the .append method instead. For more information, see Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add elements to a list?.
If you want to append the same value multiple times, see Python: Append item to list N times.
append actually changes the list. Also, it takes an item, not a list. Hence, all you need is
for i in range(n):
list1.append(i)
(By the way, note that you can use range(n), in this case.)
I assume your actual use is more complicated, but you may be able to use a list comprehension, which is more pythonic for this:
list1 = [i for i in range(n)]
Or, in this case, in Python 2.x range(n) in fact creates the list that you want already, although in Python 3.x, you need list(range(n)).
You don't need the assignment operator. append returns None.
append returns None, so at the second iteration you are calling method append of NoneType. Just remove the assignment:
for i in range(0, n):
list1.append([i])
Mikola has the right answer but a little more explanation. It will run the first time, but because append returns None, after the first iteration of the for loop, your assignment will cause list1 to equal None and therefore the error is thrown on the second iteration.
I personally prefer the + operator than append:
for i in range(0, n):
list1 += [[i]]
But this is creating a new list every time, so might not be the best if performance is critical.
Note that you also can use insert in order to put number into the required position within list:
initList = [1,2,3,4,5]
initList.insert(2, 10) # insert(pos, val) => initList = [1,2,10,3,4,5]
And also note that in python you can always get a list length using method len()
Like Mikola said, append() returns a void, so every iteration you're setting list1 to a nonetype because append is returning a nonetype. On the next iteration, list1 is null so you're trying to call the append method of a null. Nulls don't have methods, hence your error.
use my_list.append(...)
and do not use and other list to append as list are mutable.
I am trying to append objects to the end of a list repeatedly, like so:
list1 = []
n = 3
for i in range(0, n):
list1 = list1.append([i])
But I get an error like: AttributeError: 'NoneType' object has no attribute 'append'. Is this because list1 starts off as an empty list? How do I fix this error?
This question is specifically about how to fix the problem and append to the list correctly. In the original code, the reported error occurs when using a loop because .append returns None the first time. For why None is returned (the underlying design decision), see Why do these list operations return None, rather than the resulting list?.
If you have an IndexError from trying to assign to an index just past the end of a list - that doesn't work; you need the .append method instead. For more information, see Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add elements to a list?.
If you want to append the same value multiple times, see Python: Append item to list N times.
append actually changes the list. Also, it takes an item, not a list. Hence, all you need is
for i in range(n):
list1.append(i)
(By the way, note that you can use range(n), in this case.)
I assume your actual use is more complicated, but you may be able to use a list comprehension, which is more pythonic for this:
list1 = [i for i in range(n)]
Or, in this case, in Python 2.x range(n) in fact creates the list that you want already, although in Python 3.x, you need list(range(n)).
You don't need the assignment operator. append returns None.
append returns None, so at the second iteration you are calling method append of NoneType. Just remove the assignment:
for i in range(0, n):
list1.append([i])
Mikola has the right answer but a little more explanation. It will run the first time, but because append returns None, after the first iteration of the for loop, your assignment will cause list1 to equal None and therefore the error is thrown on the second iteration.
I personally prefer the + operator than append:
for i in range(0, n):
list1 += [[i]]
But this is creating a new list every time, so might not be the best if performance is critical.
Note that you also can use insert in order to put number into the required position within list:
initList = [1,2,3,4,5]
initList.insert(2, 10) # insert(pos, val) => initList = [1,2,10,3,4,5]
And also note that in python you can always get a list length using method len()
Like Mikola said, append() returns a void, so every iteration you're setting list1 to a nonetype because append is returning a nonetype. On the next iteration, list1 is null so you're trying to call the append method of a null. Nulls don't have methods, hence your error.
use my_list.append(...)
and do not use and other list to append as list are mutable.
I am writing a piece of code the this is the scenario I am facing.
How to update the list which is in for-condition, and for the next iteration, the list in for-condition is updated?
Eg.,
list = [0,1,2]
for i in list:
print list[i]
if list[i] == 0:
list.append(3)
The entry '3' should get updated in the list in for-condition.
Is it possible to update the list in for-condition dynamically?
Thanks in advance.
Yes, if you do that, it will work. However, it's usually not a good idea, because it can create confusing interactions between the iteration and the loop-body action. In your example, you add an element at the end, but if, for instance, you change an element in the middle, you may or may not see the change depending on where you are in the list when it happens. (For instance, you could change the value of an element you already iterated past.)
Also, you shouldn't name a variable list, as that shadows the built-in type called list.
Be aware that your loop is incorrect, in Python this snippet:
for e in lst:
… Iterates over each element e in lst, and e is not an index, it's an element - so all the parts in the question where you wrote list[i] are incorrect, they should have been simply i. Try this solution instead, it's equivalent and less error prone:
lst = [0, 1, 2]
print(lst)
lst += [3] * lst.count(0) # add as many 3s at the end as there are 0s in the list
Notice that it's never a good idea to modify a list at the same time you're traversing it. Also, don't use list as a variable name, there's a built-in function with that name.
As the topic states:
list = ["a", "b"]
element = "ac"
Can I use the:
if element in list:
If element is equal to the element in (list + "c")
Pseudocode to what I want to achieve:
if element in (list+c)
What is the best way to get this behavior in python?
Edit: I know there are many ways to get around this, but can this be done in one line as the code above.
More efficient would be:
if any(x+'c' == element for x in your_list):
as it avoids scanning through the list twice (once to make the "+c" versions, once to check if element is in the resulting list). It'll also "short-circuit" (that is, quickly move on) if it finds the element before going through the entire list.
P.S. - it's best not to name variables list, since that's already the name for the actual list type.
if element in [elem + 'c' for elem in my_list]:
# ...
Never a good practice to call a variable list (or int, float, map, tuple, etc.), because you are loosing those built-in types.
if element[0] in list:
You don't want to add "c" to every item in the list and check to see whether "ac" is in the resut; you want to check to see if the first letter of "ac" is in the list. It's the same thing except a lot easier.
if element[:-1] in list:
It is better to calculate the element without 'c'. So you are making just one calculation.
I have an unsorted list of integers in a Python list. I want to sort the elements in a subset of the full list, not the full list itself. I also want to sort the list in-place so as to not create new lists (I'm doing this very frequently). I initially tried
p[i:j].sort()
but this didn't change the contents of p presumably because a new list was formed, sorted, and then thrown away without affecting the contents of the original list. I can, of course, create my own sort function and use loops to select the appropriate elements but this doesn't feel pythonic. Is there a better way to sort sublists in place?
You can write p[i:j] = sorted(p[i:j])
This is because p[i:j] returns a new list. I can think of this immediate solution:
l = p[i:j]
l.sort()
a = 0
for x in range(i, j):
p[x] = l[a]
a += 1
"in place" doesn't mean much. You want this.
p[i:j] = list( sorted( p[i:j] ) )