How can I print a list "nicely" and numbered? [duplicate] - python

This question already has answers here:
Accessing the index in 'for' loops
(26 answers)
Closed 12 months ago.
I need to print a list in Python nicely and numbered. For example, if this is my list:
list = ["hello", "dad", "milk"]
this is the output I want:
[1] -hello
[2] -dad
[3] -milk
This is what I have tried:
list = ["hello", "dad", "milk"]
list_element = 0
stuff = len(list)
while stuff != list_element:
element = list[list_element]
print(f"[{list_element}] -{element}")
list_element = list_element + 1
and this is the output I get:
[0] -hello
[1] -dad
[2] -milk
but I don't know how to make it start from 1 (I know in programming you start with 0, but I want to start with 1!)
edit:
I forgot to mention this was homework and we didn't learn about the for loop yet so my teacher said I shouldn't use it as to not confuse my classmates lol

You can simply to it using enumerate in Python, as follows:
list = ["hello", "dad", "milk"]
for i, element in enumerate(list, 1): # to start with index 1, instead of 0
print(f"[{i}] -{element}")
Result:
[1] -hello
[2] -dad
[3] -milk
You can get more informatoin and example about enumerate here:
https://www.programiz.com/python-programming/methods/built-in/enumerate
In additon, one tip is that it is not good to use pre-defined keyword as a variable name such as list.

You could also use enumerate.
myList = ["hello", "dad", "milk"]
for count, element in enumerate(myList):
print(f"[{count+1}] -{element}")

Related

How can I create a list for each iteration of a for-loop? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
I'm setting up an algorithm and I do not achieve to create a list for each loop index.
I don't know how can I change the names of lists during the for-loop.
for i in range(10):
list = list.append(1 + i)
In order to get:
list0 = [1]
list1 = [2]
list2 = [3]
and so on.
My objective is to call these lists on another function, is there a way to name these lists with the list index?
I don't have find any subject which describe my issue. Maybe I don't clearly explain my problem.
It isn't efficient to create those variables, instead a dictionary would come in handy:
d = {}
for i in range(10):
d['list%s' % i] = [i + 1]
It actually could be done with:
d = {'list%s' % i: [i + 1] for i in range(10)}
To answer your question, you can do this but I think that it is not a best practice for your issue:
for i in range(10):
locals()['list{}'.format(i)] = [1 + i]
You can see that this code created 10 variables :
>>>print(list0)
[1]
>>>print(list9)
[10]
I'd prefer using a dict as in #U9-Forward answer
Instead of doing that assign them all to a reference in another list e.g.
Lst [0] = [1]
Lst [1] = [2]
This is done with:
Lst=[]
for i in range(10):
Lst.append(i+1)

How do I check if a sublist in a 2D list is in a list? [duplicate]

This question already has answers here:
Check if list contains another list in python
(2 answers)
Closed 6 years ago.
I have two lists:
my_list = [1,2,3,4,5]
my_new_list = [[1,3,7,5],[1,2,3,4,5]]
How can I check that a sublist equals my_list?
If you want to check if my_list is in the my_new_list just use in:
>>> my_list in my_new_list
True
If you want to know the index of the matching list you can use index:
>>> my_new_list.index(my_list)
1
If you think these are too efficient, too easy or too short you can do it manually as well:
>>> any(sublist == my_list for sublist in my_new_list) # equivalent to "in"
True
>>> next(idx for idx, sublist in enumerate(my_new_list) if sublist == my_list) # like "index".
1
You can index built-in function
>>> my_new_list.index(my_list)
1
Or you can use in :
>>> my_list in my_new_list
True
You can also use magic function contains
>>> my_new_list.__contains__(my_list)
True

Getting index out of range error when trying to remove a list element [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 6 years ago.
I have a list such as this:
l = ['(7 - 3)', '7 - 6', '(a + 13)']
I want to remove any expression that does NOT contain the letter "a" therefore the only expression that would be left is ['(a+13)'].
So far I have tried this:
for i in range(len(l)):
if "a" not in l[i]:
l.pop(i)
else:
print(l[i])
However I am getting a list index out of range error, and do not know how to fix this.
Could anyone help resolve this?
l.pop() removes elements from the list, so your list is getting smaller but you are not adjusting your iteration.
>>> x = [1,2,3]
>>> x.pop(0)
1
>>> x
[2, 3]
>>> x.pop(1)
3
>>> x
[2]
>>> x.pop(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
I would suggest you take a different approach. You could iterate over the elements of the list directly and print the ones that have "a" in them.
for i in l:
if "a" in i:
print(i)
If you need the list to have only the elements that have "a" in them at the end of your iteration, perhaps you would like to add those items to a new list.
things_with_a_in_them = []
for i in l:
if "a" in i:
things_with_a_in_them.append(i)
print(i)
If you want it to be terser...
things_with_a_in_them = [i for i in l if "a" in i]
map(print, things_with_a_in_them)
Have fun playing around with different approaches.
Never structurally manipulate a list while iterating over it! Use a conditional comprehension
l = [x for x in l if 'a' in x]
or filter:
l = filter(lambda x: 'a' in x, l)
# in Python3, you will have to convert the filter object to a list
# l = list(filter(lambda x: 'a' in x, l))
The problem is len(l) returns 3, but as soon as you pop an item, your list becomes shorter. Easiest thing to do (assuming your list isn't prohibitively giant) would be to just write a new list:
l_new = [i for i in l if "a" in i]
If you don't want to create a new list, and keep your logic with the pop, you would have to check for the len(l) everytime, you can do that by:
l = ['(7 - 3)', '7 - 6', '(a + 13)']
i = 0
while i < len(l):
if "a" not in l[i]:
l.pop(i)
else:
print(l[i])
i += 1
But as others have aswered, it would be better to create a new list with list comprehension

Python removing items from list [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 in the given format:
[['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']]
There are some elements like this in the list ['Linus Torvalds', ''] and I want to remove those. So why doesn't the following code remove them?
for i in people:
if(i[0] == '' or i[1] == ''):
print people.pop(people.index(i))
You are changing the list while iterating over it and this is the source of your problems. An approach that works is
people[:] = [p for p in people if p[0] != '' and p[1] != '']
this way a new temporary list containing only the elements you want is built and then assigned to the original list object when the operation is complete.
Or even people[:] = [p for p in people if all(p)] if you want to resize the list "in place".
You're modifying the list's length while iterating over it. That causes you to skip values. When you pop one item off the list, here's what happens (stealing from this answer):
[1, 2, 3, 4, 5, 6...]
^
That's the state of the list initially; now say 1 is removed and the loop goes to the second item in the list:
[2, 3, 4, 5, 6...]
^
And so on.
It's a bad idea to remove things from a list as you iterate over it. So, try one of these instead (Also, I think your condition is not what you want it to be - I've fixed it):
L = [['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']]
delete_these = []
for index, i in enumerate(L):
if not i[-1].strip():
delete_these.append(i)
for i in delete_these:
L.pop(i)
delete_these = map(lambda x: x-1, delete_these)
OR
L = [i for i in L if i[-1].strip()]
OR
answer = []
for i in L:
if i[-1].strip():
answer.append(i)
OR
i = 0
while i < len(L):
if not L[i][-1].strip():
L.pop(i)
else:
i += 1
Hope this helps

Python - Count elements in list [duplicate]

This question already has answers here:
How do I get the number of elements in a list (length of a list) in Python?
(11 answers)
Closed 6 years ago.
I am trying to find a simple way of getting a count of the number of elements in a list:
MyList = ["a", "b", "c"]
I want to know there are 3 elements in this list.
len()
>>> someList=[]
>>> print len(someList)
0
just do len(MyList)
This also works for strings, tuples, dict objects.
len(myList) should do it.
len works with all the collections, and strings too.
len()
it will count the element in the list, tuple and string and dictionary,
eg.
>>> mylist = [1,2,3] #list
>>> len(mylist)
3
>>> word = 'hello' # string
>>> len(word)
5
>>> vals = {'a':1,'b':2} #dictionary
>>> len(vals)
2
>>> tup = (4,5,6) # tuple
>>> len(tup)
3
To learn Python you can use byte of python , it is best ebook for python beginners.
To find count of unique elements of list use the combination of len() and set().
>>> ls = [1, 2, 3, 4, 1, 1, 2]
>>> len(ls)
7
>>> len(set(ls))
4
You can get element count of list by following two ways:
>>> l = ['a','b','c']
>>> len(l)
3
>>> l.__len__()
3
Len won't yield the total number of objects in a nested list (including multidimensional lists). If you have numpy, use size(). Otherwise use list comprehensions within recursion.

Categories

Resources