Getting character by its position instead of list values - python

I a have list like the one below:
['LDf12yiH3xpt4dtepYyqdw==', '802970-0', 'LIFETIME RENTS', 'LIFE ASSURANCE']
And I'm trying to get its values to assign them to other variables. However, when use for to loop it, I get the the char of each value according to given position.
For example, if I want to get the first element:
reg_0 = ['LDf12yiH3xpt4dtepYyqdw==', '802970-0', 'LIFETIME RENTS', 'LIFE ASSURANCE']
for i in reg_0:
print(i[0])
expected_output = 'LDf12yiH3xpt4dtepYyqdw=='
current_output = 'L 8 L L' # one char of each value, each line

Here is the solution to print just the first item.
print(reg_0[0])
Here is the solution to print each item.
for i in reg_0:
print(i)

You are printing the first element of each element of the list.
For i in reg_0: # is calling 'LDf12yiH3xpt4dtepYyqdw==' as i
and i[0] # is calling 'L'
and so on

for iterates over each element in the list. In your example, i will be the element in reg_0. If you want to iterate by index, you could do:
for i in range(0, len(reg_0)):
print(reg_0[i])
Or you could simply access the elements directly
for i in reg_0:
print(i)

What you are currently doing is:
for i in reg_0:
Here, you are iterating over the elements of the list. print(i[0]) is printing the first letter of the element because i is assigned an element from the list when it iterates and you are indexing the first element of i. So, here is some sample:
for i in reg_0:
print(i[0])
It is doing the following:
i='LDf12yiH3xpt4dtepYyqdw=='
i[0]='L' # printed
i='802970-0'
i[0]='8' # printed
i='LIFETIME RENTS'
i[0]='L' # printed
i='LIFE ASSURANCE'
i[0]='L' # printed
If you simply want the first element of the list, then do reg_0[0]
reg_0 = ['LDf12yiH3xpt4dtepYyqdw==', '802970-0', 'LIFETIME RENTS', 'LIFE ASSURANCE']
print(reg_0[0])

Related

Removing last list element by popping

I have the following piece of Python code where I am trying to empty out list A by removing one element at a time starting from the end. I cannot seem to reduce the list to an empty one and I would like to know why not. Any insight would be extremely appreciated.
A = [3,4,5,6,2]
for i in A:
A.pop()
var = [3,4,5,6,2]
for x in range(len(var)):
a = var.pop(-1)
print(a)
or reverse a list
var = var[::-1]
This issue you are facing because you are trying to iterate the loop from first element and trying to remove the last element of the list. at one pint for loop runs out of element in a list hence it stops and you don't get empty list.
The proper solution will be to reverse iterate through the list and remove the elements.
Sample Code :
A = [3,4,5,6,2]
for i in range( len(A) -1 , -1, -1):
A.pop()
print (A)
You can try this:
A = [3,4,5,6,2]
for a in range(len(A)):
A.pop(-1)
Output:
>>> A
[]
You can also use a list comprehension instead of a traditional for loop:
A = [3,4,5,6,2]
[A.pop(-1) for a in range(len(A))]
Output:
>>> A
[]
Here you are trying to iterate through the elements of a list while the length of the list is reduced by 1 for each iteration.
This is not the right way to do this,
Try this,
A = [3,4,5,6,2]
for _ in range(len(A)):
A.pop()
This will work.
Note: Never loop through a list in which you are going to perform some operations inside the loop-body. Try duplicating the list or use some other conditions.

Python: Accessing specific sublist element

Is there a way to be able to access specific sublist element?
For example:
list = [["a","b"],["c","d"]]
how to print out only b??
Thanks!
Firstly, it is a bad practice to name a variable as list as it is a keyword in Python. Say, it is changed to lis
lis = [["a","b"],["c","d"]]
To access b, you need to first get to the first element of lis, by lis[0]. This gives ["a", "b"]. Now you need to further go into it, so you do lis[0][1], This gives the 1-indexed element of lis[0], i.e., 'b'
You need to select the first sublist in your list (index 0), and then the second element of your sublist (index 1).
Result is list[0][1].

Print all elements of a list preceded by a given one

I want to print all the elements of this list who are directly following "apple".
With
my_list = ["apple","train","apple","bus"]
I would expect the output:
(train,bus)
But my current code
print (my_list[my_list.index("apple") + 1])
only outputs the first one, "train".
How can I get all of them?
If you want to get all items directly following an "apple" in your list, your could use a list comprehension, like:
my_list = ["apple","train","apple","bus", "apple"]
[my_list[i+1] for i, item in enumerate(my_list)
if item == "apple" and i+1 < len(my_list)]
# ['train', 'bus']
We keep the next element whenever the current one is "apple" - and we're not at the end of the list.
my_list = ["apple","train","apple","bus"]
index = my_list.index("apple")
print(my_list[index:index+2])
Have a look at Python's slice syntax. This will print the sublist from index to index + 2 (exclusive).
If you want it as a tuple as you indicated in your question, just wrap it in tuple()
Edit: Of course given that you already have apple you could also just do
print(("apple", my_list[my_list.index("apple") + 1)

How can you loop over lists of tuples where you compare the tuple in one list to the other tuples in the same list?

for x in check:
this = sorted(x) #the first tuple
for y in check:
that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
if this == that:
check.remove(x)
print(check)
I basically want to check for every list (in the list 'check') if there are tuples that are the same, such as (1, 3) and (3, 1). Then I want to remove the the last one ((3,1)) out of the list 'check'. However, the function returns a "list.remove(x): x not in list" error when I use "check.remove(x)". When I used "check.remove(y)", the result was :
output of "check.remove(y)"
I noticed that the first tuple (of the tuple with the same value) got deleted and that in the second last list, that there is still a pair of tuples that have the same values.
How the list 'check' looks like
How can I compare the tuples with each other in the same list and remove the second one that contains the same values?
Repeated removal from a list is never a good a idea since it is O(N).
You can do the cleaning in one non-nested run-through, however. It is better to build a clean list from scratch and possibly reassign it to the same variable:
seen, no_dupes = set(), []
for c in check:
s = tuple(sorted(c))
if s not in seen:
seen.add(s)
no_dupes.append(c)
# check[:] = no_dupes # if you must
Use in and not ==
for x in check:
this = sorted(x) #the first tuple
for y in check:
that = sorted(y) #the other tuples in the list? in order to compare with 'this'.
if this in that:
check.remove(x)
# alternatively you might need to loop through this if its a tuple of tuples
# for t in this:
# if t in that:
# check.remove(x)
print(check)
Consider the instance [(1,1), (1,1), (1,1)]
In the first iteration, x is assigned to the first element in the list, y is also assigned to the first element, since x=y, remove x. Now when y is iterated to the second element, x=y, but now x has already been removed in the previous iteration. You should use dynamic programming:
new_check = []
for x in check:
this = sorted(x)
if x not in new_check:
new_check.append(x)
return new_check

Searching for substring in element in a list an deleting the element

I have a list and I am trying to delete the elements that have 'pie' in them. This is what I've done:
['applepie','orangepie', 'turkeycake']
for i in range(len(list)):
if "pie" in list[i]:
del list[i]
I keep getting list index out of range, but when I change the del to a print statement it prints out the elements fine.
Instead of removing an item from the list you're iterating over, try creating a new list with Python's nice list comprehension syntax:
foods = ['applepie','orangepie', 'turkeycake']
pieless_foods = [f for f in foods if 'pie' not in f]
Deleting an element during iteration, changes the size, causing IndexError.
You can rewrite your code as (using List Comprehension)
L = [e for e in L if "pie" not in e]
Something like:
stuff = ['applepie','orangepie', 'turkeycake']
stuff = [item for item in stuff if not item.endswith('pie')]
Modifying an object that you're iterating over should be considered a no-go.
The reason to why you get a error is because you change the length of the list when you delete something!
Example:
first loop: i = 0, length of list will become 1 less because you delete "applepie" (length is now 2)
second loop: i = 1, length of list will now become just 1 because we delete "orangepie"
last/third loop: i = 2, Now you should see the problem, since i = 2 and the length of the list is only 1 (to clarify only list[0] have something in it!).
So rather use something like:
for item in in list:
if "pie" not in item:
new list.append(item)
Another but longer way would be to note down the indexes where you encounter pie and delete those elements after the first for loop

Categories