Array.extend(string) adds every character instead of just the string - python

I am trying to extend an element to a list in Python, however, instead of extending the string in the index 'i' it extends every character of the string in the index 'i'.
For example I have a list called 'strings' with just a string 'string1' and an empty list called 'final_list'.
I want to extend the first element of 'strings' to the 'final_list', so I do final_list.extend(strings[0]). But instead of the 'final_list' to end with a length of 1, corresponding to the string inserted, the list ends up with a length of 7.
If it helps, this is my code:
con = connect()
i = 0
new_files = []
while i < len(files):
info_file = obter_info(con, files[i])
if info_file [5] == 0: #file not processed
new_files.append(files[i])
i += 1
Does anyone know how can I make this to work?

The extend method takes an iterable as an argument, unpacks that iterable and adds each element individually to the list upon which it is called. In your case, you are "extending" a list with a string. A string is an iterable. As such, the string is "unpacked" and each character is added separately:
>>> d = []
>>> d.extend('hello')
>>> print(d)
['h', 'e', 'l', 'l', 'o']
If you simply want to add one element of a list to another list, then use append. Otherwise, surround the string in a list and repeat the extend:
>>> d = []
>>> d.extend(['hello'])
>>> print(d)
['hello']

try that one:
final_list.extend([strings[0]])
or:
final_list.append(strings[0])

Related

How to get all the elements an unknown length python list?

I have a list:
>>> my_list = ['a', 'b', 'c', 'd']
And I have a string which contains {} markers for the format method:
>>> my_string = 'First element = "{}" and the Second element = "{}"'
I want to interpolate the first elements from my_list into my_string like this:
>>> print my_string.format(my_list[0], my_list[1])
First element = "a" and the Second element = "b"
However, When I write the code:
I don't know how many {}s there will be in my_string
I don't know how many elements there will be in my_list
I do know that the number of elements in #2 will be greater than or equal to #1.
What python expression can I use to do the interpolation given facts number 1, 2 and 3?
You can use the splat operator: ("unpacking argument lists" officially)
print(my_string.format(*my_list))
It converts each element into another positional argument.

How to remove items from a list without the [''] part

I am trying to get the word "Test" by taking each character out of the list using positions within it.
Here is my code:
test1 = ["T", "E", "S", "T"]
one = test1[0:1]
two = test1[1:2]
three = test1[2:3]
four = test1[3:4]
print(one, two, three, four)
At the moment my output from the program is:
['T'] ['E'] ['S'] ['T']
Although that does read "Test" it has [] around each letter which I don't want.
[a:b] returns a list with every value from index a until index b.
If you just want to access a singe value from a list you just need to point to the index of the value to access. E.g.
s = ['T', 'e', 's', 't']
print(s[0]) # T
print(s[0:1]) # ['T']
The problem is you are using slices of the list not elements. The syntax l[i1,i2] returns a list with all elements of l between the indices i1 and i2. If one of them is out of bound you get an error. To do what you intended you can do:
one = test[0]
two = test[1]
...
You have slicing and indexing confused. You are using slicing where you should use indexing.
Slicing always returns a new object of the same type, with the given selection elements. Slicing a list always gives you a list again:
>>> test1 = ["T","E","S","T"]
>>> test1[1:3]
['E', 'S']
>>> test1[:1]
['T']
while indexing uses individual positions only (no : colons to separate start and end positions), and gives you the individual elements from the list:
>>> test1[0]
'T'
>>> test1[1]
'E'
Not that you need to use indexing at all. Use the str.join() method instead; given a separator string, this joins the string elements of a list together with that delimiter in between. Use the empty string:
>>> ''.join(test1)
'TEST'
try this
test1 = ["T","E","S","T"]
final = ""
for i in range(0, len(test1)):
final = final + str(test1[i])

Not able to delete string item with colon in python list

So I'm having the following problem while coding in python: I have a few string items in a list like so:
['X','Y','Z','A', 'B:C', 'D']
I want to delete everything past 'Z'. I use the following code to attempt this:
for item in lines:
if ((item == "A")):
lines.remove(item)
if (item == "B:C"):
lines.remove(item)
if (item == "D"):
lines.remove(item)
A and D get removed perfectly. However, B:C is not removed and stays in the list...
Mind you, A, D, B:C etc represent strings, not characters (e.g. A could be Transaction failed! and B:C can represent WRITE failure: cannot be done!)
How can this be solved?
Modifying a list while iterating over it is usually a bad thing. Some of the elements get skipped when you remove the current element. You may be able to fix it by iterating over reversed(lines), but it is better to create a new list that doesn't have the elements that you want to drop:
to_remove = {'A', 'B:C', 'D'}
new_lines = [line for line in lines if line not in to_remove]
Or, if you want to modify in-place:
to_remove = {'A', 'B:C', 'D'}
lines[:] = [line for line in lines if line not in to_remove]
You may use the .index() method to find the index of a specific element inside a list.
Then after finding the z_index, you may create another list by slicing the first one.
Here's an example:
l1 = ['X','Y','Z','A', 'B:C', 'D']
#finding index of element 'Z'
z_index = l1.index('Z')
#slicing list from 0 until z_index
l2 = l1[:z_index]
print l2
Output:
['X', 'Y']
Generally, it is not a good idea to delete elements from a list you are iterating. In your case, you may consider creating a new list with the result you want:
l = ['X','Y','Z','A', 'B:C', 'D']
clean_l = [i for i in l if i not in ('A', 'B:C', 'D')]
Which is a good option if you know which elements you want to delete. However, if you know that you don't want anything after 'Z' regardless of their value, then just slice the list:
clean_l = l[:l.index('Z') + 1]
Firstly you would want to find the position of 'Z' by using the index() method.
x = ['X','Y','Z','A', 'B:C', 'D']
position = x.index('Z')
Then to delete everything after z i would do this:
del x[postion+1:]
You have to add one to the position otherwise it will delete 'Z' also

Append/pop specific element of a string to the list when iterating over it

I want to know how to append and pop only specific element of a string
def letter(item):
lst = []
for i in item:
if 'a' in item:
# not sure what to put here
return lst
Output:
lst = ['a']
I only want the function to append the letter 'a' in 'apple', is that possible?
And is there a way to only remove a specific letter from a string using the list.pop() function?
If you need to use list.pop(), you can first convert your string to a list:
def find_letter(item):
lst = []
item=list(item) #convert your string to list
for index,letter in enumerate(item):
if letter=='a':
lst.append(letter) # add 'a' to your empty list
item.pop(index) # remove 'a' from the original string
item="".join(item) # convert back your list to a string
return lst,item
This gives the following output:
>>> find_letter("apple")
>>> (['a'], 'pple')
Note that you can do much simpler using list comprehension:
def find_letter(item):
word="".join([letter for letter in item if letter!='a'])
lst=[letter for letter in item if letter=='a']
return lst,word

In line.split('+')[-1] what does the -1 in the square brackets indicate in Python

Let's assume that we have this code:
name = line.split('+')[-1]
What does the -1 do? I have seen it in various codes but not sure on what it does?
And what would the difference be if there was a [0] or a [1]?
The line of code you gave is basically doing three things:
It takes the string line and splits it on +'s using str.split. This will return a list of substrings:
>>> line = 'a+b+c+d'
>>> line.split('+')
['a', 'b', 'c', 'd']
>>>
The [-1] then indexes that list at position -1. Doing so will return the last item:
>>> ['a', 'b', 'c', 'd'][-1]
'd'
>>>
It takes this item and assigns it as a value for the variable name.
Below is a more complete demonstration of the concepts mentioned above:
>>> line = 'a+b+c+d'
>>> line.split('+')
['a', 'b', 'c', 'd']
>>> lst = line.split('+')
>>> lst[-1]
'd'
>>> lst[0]
'a'
>>> lst[1]
'b'
>>> lst[2]
'c'
>>> lst[3]
'd'
>>>
Negative indexes in Python are syntactic sugar for accessing the elements in reverse order, from right-to-left, starting in -1. So -1 is the last item, -2 is the second-to-last item, and so on - the first item would be lst[-len(lst)]. For example:
lst = [1, 2, 3]
lst[-1]
=> 3
lst[-2]
=> 2
lst[-3]
=> 1
str.split returns a list:
>>> '1+2+3'.split('+')
['1', '2', '3']
list[-1] yields the last item (negative index starts from -1)
>>> '1+2+3'.split('+')[-1]
'3'
>>> '1+2+3'.split('+')[0] # the first item (Python index starts from 0)
'1'
>>> '1+2+3'.split('+')[1]
'2'
See Lists - Python tutorial (contains indexing, slicing).
Split will create list and from that you are getting the last element using [-1]
Okay, in order to understand what is happening here, we need to understand lists, split() and slicing functions of a list.
For example:
 Given the string below, let us split it:
• line ='a+b+c+d'
• name=line.split(‘+’)
 After splitting the string, it becomes a list. As shown below
• ['a','b','c','d']
 Please note: '+' is called the separator : meaning, the string will be separated based on the number of '+' available, hence the list above.
 Square brackets after the separator(always in normal parenthesis) is accessing the elements in the list
Lists are accessed using index, positive index begins with 0 (which is the first element of a list.e.g name[0] is accessing first element of the list which is ‘a’) and it operates from left to right while negative indexes starts from -1, from right to left(in the example above 'd' is index -1)
Using your sample question,
name = line.split('+')[-1] , this will return last item in the list, that is ‘d’
name = line.split('+')[0], this will return first item in the list, that is ‘a’
name = line.split('+')[1], this will return second item in the list, that is ‘b’

Categories