1
$\begingroup$

I have a list of rules: list = {a1 -> 0, a2 -> 3x, a4 -> 0, a5 -> 5x+3...}.

I would like to append to another list the nonzero rules, which are: {a2 -> 3x, a5 -> 5x+3,...}.

I have tried Select and If != 0 but they don't seem to work.

Any help is appreciated.

$\endgroup$
1
  • $\begingroup$ Sorry, but how can I append to list2 the nonzero associations of list? $\endgroup$ Commented Jun 5, 2018 at 23:13

1 Answer 1

2
$\begingroup$

Your list is a list of rules. If you want to work with associations, do:

list = Association[a1->0,a2->3x,a4->0,a5->5x+3] 

<|a1 -> 0, a2 -> 3 x, a4 -> 0, a5 -> 3 + 5 x|>

Then, there are many ways to select the nonzero associations, here are a couple examples:

Select[# =!= 0&] @ list DeleteCases[list, 0] 

<|a2 -> 3 x, a5 -> 3 + 5 x|>

<|a2 -> 3 x, a5 -> 3 + 5 x|>

Use Join to append to another association:

Join[Association[b1->1, b2->3], Select[# =!= 0&] @ list] 

<|b1 -> 1, b2 -> 3, a2 -> 3 x, a5 -> 3 + 5 x|>

Addendum

On the other hand, if you do want to work with lists of rules (as mentioned in the comments), you could do:

list = {a1->0, a2->3x, a4->0, a5->5x+3}; Select[#[[2]] =!= 0&] @ list DeleteCases[list, _->0] 

{a2 -> 3 x, a5 -> 3 + 5 x}

{a2 -> 3 x, a5 -> 3 + 5 x}

Again, use Join to join two lists of rules:

Join[{b1->1, b2->3}, DeleteCases[list, _->0]] 

{b1 -> 1, b2 -> 3, a2 -> 3 x, a5 -> 3 + 5 x}

$\endgroup$
1
  • $\begingroup$ Thanks. Is it possible to keep the list of rules and append the nonzero rules to another list (of rules)? $\endgroup$ Commented Jun 5, 2018 at 23:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.