I've been using Python for a long time, but I've recently discovered a new way of creating and iterating through lists:
l = [x for x in range(0, 10)]
This produces a list from 0 to 9. It's very useful, and much simpler than what I had been doing before:
l = []
for x in range(0, 9):
l.append(x)
Now that I understand this way of doing things, I've been using it for a lot of stuff, and it's working out great. The only problem is, I sometimes want another option. For example, if I have a list full of 1's and 0's:
import random
l = [random.randint(0, 1) for i in range(0, 10)]
I want to take this list and iterate through again, only do two different things based on an if else statement:
for idx, item in enumerate(l):
if item == 1:
l[idx] = 'A'
else:
l[idx] = 'B'
I know it would be easier to just create a list full of random instances of 'A'
and 'B'
, but this is just an example, it won't work in my use case. How would I use my new way of creating lists to do this? I know how to add an if statement on the end:
l = [x for x in range(0, 10)]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l = [x for x in range(0, 10) if i != 7]
# [0, 1, 2, 3, 4, 5, 6, 8, 9]
But what about my else statement? And, incidentally, what is this way of creating lists called? I might have been able to find an answer online if I knew.