User Tools

Site Tools


python_lists

dummy

tasks

search one list in another

>>> letters = [i for i in 'abcdefghijklmnopqrstuvwxyz']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> name = [i for i in 'kamaraju']
>>> name
['k', 'a', 'm', 'a', 'r', 'a', 'j', 'u']
>>> indices = [letters.index(i) for i in name]
>>> indices
[10, 0, 12, 0, 17, 0, 9, 20]
>>> rebuilt_name = [letters[i] for i in indices]
>>> rebuilt_name
['k', 'a', 'm', 'a', 'r', 'a', 'j', 'u']

tags | identify the indices

read file as list of strings

fname = "foo.txt"
with open(fname, "r") as fh:
  lines = [line.rstrip() for line in fh]

Check if a variable is a list

% python
Python 3.11.4 (main, Jul  5 2023, 13:45:01) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(['foo'], list)
True
>>> isinstance('foo', list)
False
python_lists.txt · Last modified: 2024/08/07 19:39 by raju